How to center absolute div horizontally using CSS?
I've a div and want it to be centered horizontally - although I'm giving it margin:0 auto;
it's not centered...
.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;
}
You need to set left:0; right:0;
left:0; right:0;
.
This specifies how far to offset the margin edges from the sides of the window.
http://www.w3.org/TR/CSS2/visuren.html#position-props
http://jsfiddle.net/SS6DK/
CSS
.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;
}
Note: You must define the width
or this answer will not work . That means this answer is not useful for elements with dynamic widths.
This doesn't work in IE8 but might be an option to consider. It is primarily useful if you do not want to specify a width.
.element
{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Although above answers are correct but to make it simple for newbies, all you need to do is set margin, left and right. following code will do it provided that width is set and position is absolute:
margin: 0 auto;
left: 0;
right: 0;
Demo:
.centeredBox {
margin: 0 auto;
left: 0;
right: 0;
/** Position should be absolute */
position: absolute;
/** And box must have a width, any width */
width: 40%;
background: #faebd7;
}
<div class="centeredBox">Centered Box</div>
链接地址: http://www.djcxy.com/p/75822.html
上一篇: 用动态宽度居中固定div(CSS)
下一篇: 如何使用CSS水平居中绝对div?