【问题标题】:Equal vertical space between images and lines of text图像和文本行之间的垂直间距相等
【发布时间】:2015-06-08 18:37:07
【问题描述】:

我正在尝试将设计转换为 HTML/CSS,图像和文本之间的垂直间距相等,但无法这样做。设计师在图片、标题和 desc 之间创建了 20px 的边距,但由于 CSS 处理行高的方式,所有这些元素之间的空间并不相同。

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

【问题讨论】:

  • 你希望你的输出是怎样的?
  • 我希望每个元素下方有 20 像素的边距,并且实际上在浏览器中看起来是这样的。
  • 这个问题没有简单的解决方法。您的选择是在每个项目上创建负边距以将它们“减少”到适当的间距,或者根据元素组合具有不同的边距。
  • @JesseKernaghan 我不敢苟同。有一个简单的解决方案。
  • 你好,图片的大小是多少,从什么到什么(div 中的任何背景,或边框?) div 到 div 或 text to text to image 的 20px 边距?

标签: css baseline


【解决方案1】:

你在正确的轨道上。将需要20px边距的元素的line-height设置为1。设置为1 意味着行高将等于当前字体大小,如字体大小的100%。一些例子:

line-height: 1

字体大小 = 20,行高 = 20

line-height: 1.5

字体大小 = 20,行高 = 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/

对于.teaser-image,我将字体大小设置为零,以便从图像周围移除下降高度。

【讨论】:

  • 这没有解决。 teaser-desc 文本实际上需要有 line-height: 21.6px;字里行间。
  • 那么你必须从.teaser-desc的边距中减去1.6px。做起来也不难。如果要增加超出字体大小的行高,则必须相应地调整边距。
【解决方案2】:

如果是关于图像不站在边缘,那么,vertical-align 应该是重置的东西:

.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

【讨论】: