Reputation:
Every example of using CSS to horizontally center an element that I have seen so far says to set the margin-left
and margin-right
to auto
. I'm not very experienced in CSS, so I'm wondering if there's a reason to set both those properties rather than just setting one or the other to 50%
? Would there be side-effects?
Upvotes: 0
Views: 204
Reputation: 654
Setting the left margin to 50% will cause the left edge of the box to be centered, which is not quite the same as having the entire box centered.
Another approach which is commonly used is to set the left
property to 50%
, setting a fixed width, and setting the left margin to be negative one half of the fixed width.
Upvotes: 0
Reputation: 968
You added the css3
tag to your question. One option in modern Browsers (http://caniuse.com/#feat=flexbox) is to use Flexbox. Add display: flex; justify-content: center
to the parent. This will center its children.
CSS Tricks has an excellent guide to Flexbox: http://css-tricks.com/snippets/css/a-guide-to-flexbox/
Upvotes: 1