CSS:拉伸内联元素以填充可用宽度

时间:2014-10-16 17:05:52

标签: css

我有一个带有文本的页面,一些图像浮动到右边,文本会四处流动。

我想在带有下划线的文本中添加一个标题(实际上它是border-bottom我认为在这种情况下会更容易吗?)...现在,我的问题是我想要标题( h3)元素(以及下划线/下边框)可以很好地拉伸,直到它(几乎)击中图像。

这是jsfiddle

h3 {
  border-bottom:1px solid #000;
}
img {
  float: right;
  margin-left:15px;
  display:block;
  width:40%;
  height:200px;
  background-color:green;
}
<div>
  <img src="#" alt="This is my image">
  <h3>This is my title</h3>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque totam cumque accusantium repellendus, illum, libero reiciendis est, explicabo obcaecati asperiores suscipit eum? Perferendis ipsa odio maxime, ullam, iste vero! Quis!</p>          
</div>

使用h3标记,它几乎可以正常工作,但它不尊重图片上的margin-left

如果图像不存在,我希望下划线/边框在页面上向右伸展,所以我不想手动指定宽度。

有解决方案吗?

1 个答案:

答案 0 :(得分:4)

授予<h3>财产overflow:hidden。这可以防止标题超出浮动元素:

h3 {
    border-bottom:1px solid #000;
    overflow:hidden;
}
img {
    float: right;
    margin-left:15px;
    display:block;
    width:40%;
    height:200px;
    background-color:green;
}
<div>
    <img src="#" alt="This is my image">
     <h3>This is my title</h3>

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque totam cumque accusantium repellendus, illum, libero reiciendis est, explicabo obcaecati asperiores suscipit eum? Perferendis ipsa odio maxime, ullam, iste vero! Quis!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque totam cumque accusantium repellendus, illum, libero reiciendis est, explicabo obcaecati asperiores suscipit eum? Perferendis ipsa odio maxime, ullam, iste vero! Quis!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque totam cumque accusantium repellendus, illum, libero reiciendis est, explicabo obcaecati asperiores suscipit eum? Perferendis ipsa odio maxime, ullam, iste vero! Quis!</p>
</div>

A relevant read