Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra space from line-height when vertically aligning things with CSS

Tags:

css

I often have to vertically align an image with a block of text next to it.

Like so:

It the problem is that because of the line-height of the text, there is the appearance of an extra space above the text:

I can't just remove the line-height because this is a multiline text block that needs a luxuriously large line height.

The only solution I've come up with is to apply a margin-top: -5px to the top of the text so it becomes optically aligned with the image.

However this seems like a brittle solution since any change to the line-height of the page will throw off the alignment.

Is there a more bulletproof solution?

like image 912
Christian Schlensker Avatar asked Oct 20 '22 12:10

Christian Schlensker


2 Answers

style the text as you will..

And just wrap a div around that area of text, to define where you want this area to be on the page.

(IMO more stable / semantic / and cross browser friendly then styling <p> or <span> tags alone for positioning.)

<article class="cooltext">

<span class="nacholibre">one time at band camp...</span>

</article>

css

.cooltext { 
   margin-top:-4px; // where you want this in the page
   width: 200px; // however in relation to layout
   height: 150px; // however in relation to layout
}


.nacholibre { 
   line-height: 12px; // text formatting
   display: inline-block;
}
like image 63
fred randall Avatar answered Jan 04 '23 05:01

fred randall


You can make this work as @HonoreDoktorr mentioned in the comments, using vertical-align: text-top is the proper way to align it. This style needs to be added to the img tag or a css class on the image tag. See examples of its application

https://developer.mozilla.org/en/docs/Web/CSS/vertical-align

Here are 2 examples of using different html structure

http://jsfiddle.net/wq46xs5v/1/

http://jsfiddle.net/wq46xs5v

These code might resemble what you have

<div>
    <div class="image"><img src="http://zoarchurch.co.uk/content/pages/uploaded_images/91.png" /></div>

    <div class="text">dfgdfg</div>
</div>

CSS

img {
    vertical-align: text-top;
}
div {
    line-height: 40px;
    margin: 0;
}
.image, .text {
    float: left;
}

The magic here is vertical-align: text-top;. I put the style on the img tag but you can easily add a class to the image that needs it so not all images have that style. Note the line-height is set on the div containing the image and the text so they will match up correctly. Tested on FF and chrome

You can also take a look http://www.brunildo.org/test/va_lineheight.html for a good visualization of the vertical alignment

like image 22
Huangism Avatar answered Jan 04 '23 07:01

Huangism