Equal vertical space between images and lines of text

1.8k views Asked by At

I am trying to convert a design to HTML/CSS with equal amount of vertical space between the image and text, but unable to do so. The designer created this is 20px margin between the image, title, and desc, but due to the way CSS is processed with line height, the space is not the same between all these elements.

http://jsfiddle.net/r9370Lxr/

 <div class="teaser-image">
     <img src="teaser1.png">
 </div>
 <div class="teaser-title">At Your Service</div>
 <div class="teaser-desc">
     blah blah blah
 </div> 


.teaser-image, .teaser-title, .teaser-desc {
    margin-bottom: 20px;
    line-height: 21.6px;
 }

.teaser-title {
    font-family: "myriad-pro-condensed",sans-serif;
    font-weight: 700;
    font-size: 24px;
    text-align: center;
}

.teaser-desc {
   font-size: 16px; 
   font-family: "myriad-pro-condensed",sans-serif;
   text-align: center;
}
2

There are 2 answers

2
hungerstar On BEST ANSWER

You're on the right track. Set the line-height of the elements that need the 20px margin to 1. Setting to 1 means that the line height will be equal to the current font size, as in, 100% the font size. Some examples:

line-height: 1

font size = 20, line height = 20

line-height: 1.5

font size = 20, line height = 30 (20 x 1.5)

HTML

 <div class="teaser-image">
     <img src="http://placehold.it/500x50/">
 </div>
 <div class="teaser-title">At Your Service</div>
 <div class="teaser-desc">
     blah blah blah
 </div> 

CSS

.teaser-image,
.teaser-title,
.teaser-desc {
    margin: 20px 0;
    line-height: 1;
 }
.teaser-image {
    font-size: 0;
}
.teaser-title {
    font-family: "myriad-pro-condensed",sans-serif;
    font-weight: 700;
    font-size: 24px;
    text-align: center;
}
.teaser-desc {
   font-size: 16px; 
   font-family: "myriad-pro-condensed",sans-serif;
   text-align: center;
}

jsFiddle: http://jsfiddle.net/2ojvpp53/

For .teaser-image I set the font size to zero so that the descender height is removed from around the image.

0
G-Cyrillus On

if it is about image not standing at the edge, then, vertical-align should be the thing to reset:

.teaser-image, .teaser-title, .teaser-desc {
    margin-bottom: 20px;
    line-height: 21.6px;    
  text-align: center;
  box-shadow:inset 0 0 0 1px;/* show me ! */
 }

.teaser-title {
    font-family: "myriad-pro-condensed",sans-serif;
    font-weight: 700;
    font-size: 24px;
    text-align: center;
}

.teaser-desc {
   font-size: 16px; 
   font-family: "myriad-pro-condensed",sans-serif;
   text-align: center;
}

img {vertical-align:top;}/* get close to me :) */
 <div class="teaser-image">
     <img src="http://dummyimage.com/100x100&text=teaser">
 </div>
 <div class="teaser-title">At Your Service</div>
 <div class="teaser-desc">
     blah blah blah
 </div> 

http://codepen.io/gc-nomade/pen/ZGKjLW