CSS centering gives different results
Consider this code to center a div relative to it's parent element:
div {
width:200px;
position:absolute;
left:50%;
margin-left:-110px;
padding:10px;
display:table;
}
We are using (width/2) - padding, right?
Why is it that all Webkit based browsers (Safari and Chrome) center this div 10px to much to the left? This 10px is the padding.
So we have two fronts here:
- Chrome + Safari -> padding must no be included to center correctly
- Firefox, IE, Opera -> padding must not be included to center correctly
Now my question is, which one of both is actually doing it right?
EDIT:
Apperantly; the problem only occurs when adding disp开发者_如何学编程lay:table; to the div. Made an example: http://jsfiddle.net/rhKW7/1/link text
I am not able to recreate your issue. Your code works across browsers.
Live demo: http://jsfiddle.net/SXzbF/1/
Edit: I figured out what the issue is:
In Chrome (at least), if you set display:table
, then as a result the padding of that element is not used. I guess, that's because, for TABLE elements, padding is only set to TD element (to the cells), and not to the TABLE element. I am not sure if setting padding on TABLE is valid, but I recommend you to not do it, but instead set the padding on the cells.
You are doing it wrong. You should use
margin: 0 auto;
That will center the element in its parent.
Depending on your implementation you could contain the element that needs to be centered in a div that is 100% width and absolutely positioned and then with the current element that you have use the margin:0 auto to center it within the absolutely positioned element.
精彩评论