If you've ever tried to vertically align some text inside a div, you might notice that it's pretty annoyingly difficult. I just found myself with the following scenario:
I wanted to create something that looked like this:
And I wanted to use a single css class to style the div which would contain the image as a background and have the text vertically aligned.
I created the background image with the exclamation mark, and then positioned it on the left like so:
.verticallyAlignedDiv {
height: 50px;
background: url("exclamationMark20pxhigh.png") no-repeat scroll 0 0 transparent;
}
When I added the text it was aligned on the top and was overlapping the background. I then added padding on the left (to indent the text), and on the top (to separate it from the top of the div).
.verticallyAlignedDiv {
height: 50px;
background: url("exclamationMark20pxhigh.png") no-repeat scroll 0 0 transparent;
padding-left: 37px;
padding-top: 15px;
}
This did NOT work because adding padding on top pushed the height of the whole thing, creating extra unwanted space on the bottom.
Solution:
You want to use the vertical-align attribute. However, this only will work on something with a fixed height, so I changed my height attribute to be a line-height , and then I could use the vertical-align.
Like this:
.verticallyAlignedDiv {
line-height: 50px;
background: url("exclamationMark20pxhigh.png") no-repeat scroll 0 0 transparent;
padding-left: 37px;
vertical-align: middle;
}
and that's another good job well done
:)
No comments:
Post a Comment