I have a certain class of div
that contains an icon in the upper-left corner as the background image, and text in the remainder of the div
. The div
has a minimum height of 32px so that all of the icon is shown.
When there is multiple lines of text, the lines look fine as they stretch the div
down longer than the minimum height, but when there is only one line, it is not vertically aligned with the centre of the icon.
JSFiddle here.
Is there any way to get the single line to vertically align, but not mess it up when there are multiple lines?
.test {
background-color: #98c5ff;
color: #093d80;
width: 400px;
min-height: 32px;
background-image: url("http://google.com/favicon.ico");
background-repeat: no-repeat;
padding-left: 42px;
}
<div class="test"><p>Short message</p></div>
<hr />
<div class="test"><p>Rather long message that should hopefully wrap on to a second line at some point.</p></div>
<hr />
<div class="test"><p>Message<br />with<br />many<br />lines<br />.</p></div>
Answer: Use the CSS line-height property Suppose you have a div element with the height of 50px and you have placed some link inside the div that you want to align vertically center. The simplest way to do it is — just apply the line-height property with value equal to the height of div which is 50px .
The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.
You can use display
in your CSS like this:
.test {
background-color: #999999;
display: table; /* Add this in here. */
width: 400px;
min-height: 32px;
background-image: url("http://google.com/favicon.ico");
background-repeat: no-repeat;
padding-left: 42px;
}
.test p {
display: table-cell;
vertical-align: middle;
}
display:flex
is also an option for .test
.
if .test
holds a single p
then margin:auto 0;
should be enough:
http://jsfiddle.net/eXZnH/35/ EDIT: (fixed fiddle) http://jsfiddle.net/eXZnH/36/
.test {
background-color: #98c5ff;
color: #093d80;
width: 400px;
min-height: 32px;
background-image: url("http://google.com/favicon.ico");
background-repeat: no-repeat;
padding-left: 42px;
display: flex;/* added */
}
p {
margin: auto 0;/* added */
}
<div class="test">
<p>Short message</p>
</div>
<hr />
<div class="test">
<p>Rather long message that should hopefully wrap on to a second line at some point.</p>
</div>
<hr />
<div class="test">
<p>Message
<br />with
<br />many
<br />lines
<br />.</p>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With