我有一个 div 并希望它水平居中 - 尽管我给它 margin:0 auto;
它没有居中...
.container {
position: absolute;
top: 15px;
z-index: 2;
width:40%;
max-width: 960px;
min-width: 600px;
height: 60px;
overflow: hidden;
background: #fff;
margin:0 auto;
}
最佳答案
你需要设置left: 0
和right: 0
。
这指定从窗口边缘偏移边缘边缘的距离。
Like 'top', but specifies how far a box's right margin edge is offset to the [left/right] of the [right/left] edge of the box's containing block.
来源: http://www.w3.org/TR/CSS2/visuren.html#position-props
Note: The element must have a width smaller than the window or else it will take up the entire width of the window.
You could use media queries to specify a minimum margin, and then transition to
auto
for larger screen sizes.
.container {
left:0;
right:0;
margin-left: auto;
margin-right: auto;
position: absolute;
width: 40%;
outline: 1px solid black;
background: white;
}
<div class="container">
Donec ullamcorper nulla non metus auctor fringilla.
Maecenas faucibus mollis interdum.
Sed posuere consectetur est at lobortis.
Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
Sed posuere consectetur est at lobortis.
</div>
关于css - 如何使用 CSS 将绝对 div 水平居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17976995/