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

I often have to vertically align an image next to it next to the text.

Same:

The problem is that because of the line-height of the text, the appearance appears above the text:

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

The only solution I have come across is to apply margin-top: -5px

to the beginning of the text so that it is optically aligned with the image.

However, this seems like a brittle solution, as any change in the page line-height discards the alignment.

Is there a more bulletproof solution?

+3


source to share


3 answers


enter the text the way you want ..

And just wrap div

around that area of ​​text to define where you want that area to be on the page.

(IMO more stable / semantic / and cross-browser and then styling <p>

or <span>

just positioning tags.)



<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;
}

      

+2


source


Select p: nth-child (2) and add the line-height so the first p doesn't have it.



0


source


You can make this work like @HonoreDoktorr mentioned in the comments using vertical-align: text-top

- this is the correct way to align it. This style needs to be added to the tag img

or css class in the image tag. See examples of its application

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

Here are two examples using a different html structure

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

http://jsfiddle.net/wq46xs5v

This code may 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 is here vertical-align: text-top;

. I put the style in a tag img

, but you can easily add a class to the image you want, so not all images have this style. Note that it is line-height

set on the div containing the image and text to match the correct one. Tested on FF and chrome.

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

0


source







All Articles