IE7 +: max-width: 660px and margin: auto
You can center the block level element by setting a fixed width, and set margin-right and -left to auto.
.container ul { max-width: 660px; margin-right: auto; margin-left: auto; }
Notes
- No container required
- It requires the width or maximum width of the element to the center, which should be known π
IE8 +: display: inline-block and text-align: center
It is also possible to center the element, as well as plain text. Disadvantage: you need to assign values ββto both the container and the element itself.
.container { text-align: center; } .container ul { display: inline-block; text-align: initial; }
Notes:
- No specific width required π
- Container Required π
- Aligns the contents of the stream to the center (potentially unwanted side effect) π
- Works well with a dynamic number of menu items (i.e., in those cases where you do not know the width that one item occupies) π
IE8 +: display: table and margin: auto
Like the first solution, you use automatic values ββfor the fields on the right and left, but do not assign a width. If you don't need support for IE7 and below, this is better, although for the table type for display it seems awkward to use the value of the display property.
.container ul { display: table; margin-right: auto; margin-left: auto; }
IE9 +: transform: translatex(-50%) and left: 50%
This is similar to a fancy centering method that uses absolute positioning and negative margins.
.container { position: relative; } .container ul { position: absolute; left: 50%; transform: translatex(-50%); }
Notes
- As always, when using absolute positioning, the centered element will be removed from the document stream. All elements will only care about the container, but ignore the centered element itself. πππ
- Container Required π
- This method makes it easy to center vertically using
top instead of left and translateY() instead of translateX() . top and left also combined with translate() (note the missing X and Y ) π - Check caniuse.com for browser support, because it may require a prefix for Android browsers and / or iOS browsers (and IE9).
Cutting edge: display: flex
.container { display: flex; justify-content: center; }
Notes
- This is not a hack πππ
- Container Required π
- Browser support is not bad, but it has several notable holes, especially Internet Explorer up to version 11 and some older Android and Safari (macOS and iOS)
Lastly, a demo that summarizes all of the above solutions.
kleinfreund Jun 05 '13 at 17:34 2013-06-05 17:34
source share