图像右侧的文本

时间:2018-01-21 21:58:09

标签: css

我试图在图片右侧显示文字。出于某种原因,如果文本很短,则会正确显示。但是,如果我在文本中放置几个​​句子,它会显示在图像下方。

以下是发生了什么的示例:https://jsfiddle.net/deadendstreet/t0rtdu7c/

这是我正在使用的CSS。

.float-my-children > * {
float:left;
margin-right:5px;
}
.clearfix {
*zoom:1 /* for IE */
}

1 个答案:

答案 0 :(得分:1)

问题是您的文字位于<div>元素中,默认情况下为display: block。默认情况下, Block-level elements 的{strong> width100%,因此请尝试将自己“分开”并占用一整行。

因此,您需要做的是为文字和图片指定width,当合并时,总计 100%(在补偿边距后) 。在我的示例中,我使用 calc() 来补偿 margin-right

另请注意,您可能不希望将margin-right提供给文本(因为它是最终的兄弟),所以我只将它应用于我的示例中的图像。如果你想增加与盒子的距离,那么将padding添加到盒子本身会更有利。

/* tell the container's children to float left: */

.float-my-children>* {
  float: left;
  
}

.float-my-children > img {
  margin-right: 5px;
  width: calc(10% - 5px);
}

.float-my-children > div {
  width: 90%;
}

/* this is called a clearfix. it makes sure that the container's children floats are cleared, without using extra markup */

.clearfix {
  *zoom: 1/* for IE */
}

.clearfix:before,
.clearfix:after {
  content: " ";
  display: table;
}

.clearfix:after {
  clear: both;
}


/* end clearfix*/


/* below is just to make things easier to see, not required */

body>div {
  border: 1px dashed red;
  margin-bottom: 10px;
}
<div class="clearfix float-my-children">
  <img src="http://www.carleybakker.com/wp-content/uploads/2017/12/tonya_testimonial.png" width=50px>
  <div>“Carley’s presentation was engaging and informative. She is a strong speaker and gave the audience valuable insights.”
    <div style="font-size: 9px">-- Board of Trade</div>
  </div>
</div>

<div class="clearfix float-my-children">
  <img src="http://www.carleybakker.com/wp-content/uploads/2017/12/tonya_testimonial.png" width=50>
  <div>Carley’s presentation was engaging and informative.</div>
</div>

希望这有帮助! :)