IE8 supports table-cell
.
If you absolutely have to support IE7 - I mean have to - looking exactly the same as modern browsers, then at least use text-align: center
in the parent. At least that way, if you want to add more elements side-by-side, you can: http://jsfiddle.net/7Esg9/1/
Edit: Updated the fiddle to demonsrate the modularity of it.
IE7 is six years old. We shouldn't be filling our modern markup with stuff to support it; it's holding the Web back.
Then use a modern solution like table-cell, flexbox, or calc(), and let IE7 and below use overflow: auto
, or lock the container width and have its contents percentage-sized. http://caniuse.com/css-table
That's preferable to unnecessary wrappers (most of the time)
If you're using absolute/fixed, then use negative margins:
For a 400px-wide element:
left: 50%;
margin-left: -200px;
display: block
and margin: 0 auto
works in old IE, and doesn't need an HTML wrapper
Please don't make a wrapper where you don't need to. Use display: block
and margin: 0 auto
, or a negative margin of half the element width, or if you can use calc() use left: calc(50% - <your element width>/2)
, or if you can use flexbox use that, or display: table-cell
...
@fardjad ?comment=@fardjad (Sorry, Coderwall has a bug that replaces my "Edit/Delete" with your "Reply")
The point of removing the wrapper is less to do with cleanliness than the modularity and re-useability of the relevant CSS. The 'ugly' (and I agree it is uglier) CSS should be handled by a preprocessor anyway - centering an element horizontally in fixed/absolute positioning is something you'll need to do all the time, and that means editing the CSS will require a lot of comparatively awkward HTML editing, and quite of lot of HTML 'divitis'/bloat.
To be clear,
<div>
and<span>
are intended to be unsemantic tags, so the semantic value of the markup isn't one of my concerns here.It's also worth noting that the modern solutions I emphasised in my first comment as being strongly preferable to an IE7 workaround can look much nicer than the workaround, particularly in the case of
calc
.