Reputation: 7470
I'm centering some content (both ways) inside a container element using the method Chris Coyier suggested in CSS-tricks. For the sake of compatibility I'm using a semantic approach instead of the :before
pseudo element used in the article. For some reason Firefox (tested on v.19 for Mac) fails and I can't figure out what the right fix is (whereas Safari, Opera, IE9 and Chrome all work the way they should).
I can detect browser and put some conditional rules but I'm interested in fixing this globally if possible.
Here's my code from the modified fiddle I created if you wanna check in different browsers.
CSS:
.block {
text-align: center;
background: #c0c0c0;
margin: 20px 0;
height: 300px;
}
.content-before {
content:'';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
.centered {
display: inline-block;
vertical-align: middle;
padding: 10px;
background: #f5f5f5;
}
HTML:
<div>
<div class="block">
<span class="content-before"></span>
<div class="centered">
<h1>Some text</h1>
<p>But he stole up to us again, and suddenly clapping
his hand on my shoulder, said—"Did ye see anything
looking like men going towards that ship a while ago?"</p>
</div>
</div>
</div>
Upvotes: 0
Views: 96
Reputation: 66188
The layout is broken because the width of .centered
is 100% of the container's width, and inline-block elements don't deal with overflows well (and they get pushed to the next line).
Try setting font-size: 0
for the .block
element, then redeclaring the font-size (say, 16px) in .centered
. It worked for me - http://jsfiddle.net/teddyrised/hJtpF/4986/
.block {
font-size: 0;
/* Rest of the styles here */
}
.centered {
font-size: 16px;
/* Rest of the styles here */
}
The only drawback here is that you have to use pixel values to redeclare the font-size - em
units (which I personally use most frequently) will not work as the parent has a font-size of 0 (em
is a relative unit, and in this case, the em
will take reference from the parent font size which is 0, and anything multiplied by zero is zero).
[Edit]: If you don't want to use this dirty hack, then you can also opt to ensure that the width of the child, .centered
is not 100% of the parent container's width, so that there is some space left for the empty element .content-before
, something along the line of:
.centered {
box-sizing: border-box; /* So that padding is also taken into account */
width: 90%;
/* Rest of the styles here */
}
See fiddle for the second recommendation - http://jsfiddle.net/teddyrised/hJtpF/4988/
Upvotes: 3