Sum*_*pta 122 html javascript css
我想将一个<div>(或一个<table>)元素放在屏幕的中心,而不管屏幕大小.换句话说,"顶部"和"底部"上留下的空间应相等,"右"和"左"侧留下的空间应相等.我想用CSS完成这个.
我尝试了以下但它不起作用:
<body>
<div style="top:0px; border:1px solid red;">
<table border="1" align="center">
<tr height="100%">
<td height="100%" width="100%" valign="middle" align="center">
We are launching soon!
</td>
</tr>
</table>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
注意:
如果<div>元素(或<table>)与网站一起滚动,则要么很好.只是希望它在页面加载时居中.
ein*_*ein 188
简单的方法,如果你有一个固定的宽度和高度:
#divElement{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}?
Run Code Online (Sandbox Code Playgroud)
请不要使用内联样式!这是一个工作示例http://jsfiddle.net/S5bKq/.
Xwi*_*utX 139
随着变形越来越受到支持,你可以在不知道弹出窗口的宽度/高度的情况下做到这一点
.popup {
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
简单!JSFiddle:http://jsfiddle.net/LgSZV/
更新:请访问https://css-tricks.com/centering-css-complete-guide/,获取有关CSS中心的详尽指南.将它添加到这个答案,因为它似乎得到了很多关注.
Eri*_*ner 27
设置宽度和高度,你很好.
div {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 200px;
}
Run Code Online (Sandbox Code Playgroud)
如果您希望元素维度灵活(并且不关心旧版浏览器),请使用XwipeoutX的答案.
lum*_*men 18
它适用于任何对象.即使你不知道大小:
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*eón 16
现在,使用HTML 5和CSS 3更容易:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body > div {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
}
</style>
</head>
<body>
<div>
<div>TODO write content</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
elc*_*nrs 12
如果你有一个固定的div绝对位置,它从顶部50%,左边50%,负边距分别是高度和宽度的一半左右.根据您的需求调整:
div {
position: absolute;
top: 50%;
left: 50%;
width: 500px;
height: 300px;
margin-left: -250px;
margin-top: -150px;
}
Run Code Online (Sandbox Code Playgroud)
我会在 CSS 中这样做:
div.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
然后在 HTML 中:
<div class="centered"></div>
Run Code Online (Sandbox Code Playgroud)
使用flex.更简单,无论您的div尺寸如何都可以使用:
.center-screen {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
min-height: 100vh;
}Run Code Online (Sandbox Code Playgroud)
<html>
<head>
</head>
<body>
<div class="center-screen">
I'm in the center
</div>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
405226 次 |
| 最近记录: |