tags:

views:

27

answers:

2

help me

I am trying to accomplish this with CSS. Here is my markup:

<h2>
  <img src="A.gif" alt="A" width="30" height="30" />
  <img src="B.gif" alt="B" width="30" height="30" />
  18 pt; vertically centered;
</h2>
  • A and B are 30x30 pixel images.
  • Small red lines are 5 pixels paddings/margins (whichever works)
  • As a result of the images' height and vertical padding, the outermost container has a height of 40px (30+5+5).
  • The width of the outermost container is 100%.

Note: There is no chance the 18pt text will overflow the width of the container. Assume it will always be one line.

Note: If more markup would help get the desired view, the markup can be modified.

How can this be accomplished?

A: 

You can set the line-height to 40px, that should cause the text to be vertically centred if it is only one line.

h2 {
    line-height: 40px;
}
h2 img {
    padding: 5px;
    vertical-align: middle;
}
jeroen
@jeroen, I tried this and the text sink to the bottom of the `h2`.
macek
@macek: it works for me in Firefox, even without the padding on the images. Do you have a doctype set?
jeroen
@macek: I see that IE8 is making trouble and needs a `vertical-align:middle`, I´ll edit the answer....
jeroen
+1  A: 

If I'm not mistaken, you can use the vertical-align: text-bottom property on an img to achieve this kind of result.

Here's a little test: http://www.w3schools.com/Css/tryit.asp?filename=trycss_vertical-align

You can try removing the styles there and replacing them with
img { vertical-align: text-bottom; }
and the text should be aligned to the desired centre of the page element.

alexcoco
@alexcoco, the `img` isn't having trouble as much as the text is.
macek
@macek Yeah, I see the problem, try it out though. It was strange to me that you need to specify the alignment for the text using the `img` style but it does vertically align the text. I haven't tried it for large paragraphs but for simple small lines it works fine.
alexcoco
Also, like joroen mentioned, you can set the `line-height` of the text to the same number of pixels as the height of the container (which is 30px from what I can gather, I don't think padding has to be accounted for).
alexcoco
@alexcoco, I played around with `vertical-align:` property but `middle` value didn't end up being the best. `vertical-align: text-bottom;` renders very closely to the expected output. +1 for recommending this. Works in FF/Chrome/Safari/IE. Update your answer to show `text-bottom` and I'll mark it as accepted :)
macek