首页 文章

有一个段落和图像适合固定div

提问于
浏览
0

我计划 Build 几个div,包括一个段落和一个图像 . 图像的大小和段落都是不同的 . div具有固定的高度,图像高度将更改为适合段落后的其余高度 . 图像应该完全显示在div上,这意味着我无法溢出:隐藏在div上

.container {
  border: 1px solid #000;
  height: 250px;
}
<div class='container'>
  <p>This is random information, the height could be differnet depened on the content of the paragraph</p>
  <a href='http://google.ca'>
    <img src="http://lorempixel.com/300/200/nature/">
  </a>
</div>

但是,大多数时候图像都会溢出,有没有解决方案我只能通过css将图像融入div中?

3 回答

  • 0

    我不确定我是否完全理解,但如果你想让图像不突破它的容器,你可以简单地将容器设置为溢出:隐藏;这样,它将包含在容器中 .

  • 0

    您可以将CSS添加到图像本身 . 这将根据父级的尺寸确定图像的 max-heightmax-width . 在这种情况下, height: 250px; . 唯一的问题是,如果你想要填充,你必须在图像的 max-height 上添加 calc (以扣除填充) .

    Note that I have added "Normalize CSS" on this fiddle

    https://jsfiddle.net/7yjhz0dc/2/

    .container {
      border: 1px solid #000;
      height: 250px;
      padding: 20px;
    
      a {
        display: block; // you always want this or inline-block for anchor tags wrapped around images, so the whole image is clickable
      }
    
      p {
        margin-top: 0;
      }
    }
    
    .img-responsive {
      display: block;
      max-width: 100%;
      max-height: calc(100% - 20px);  // 20px is the parent container's padding
    }
    

    HTML

    <div class='container'>
      <p>This is random information, the height could be differnet depened on the content of the paragraph</p>
      <a href='http://google.ca'>
        <img src="http://lorempixel.com/800/500/nature/" class="img-responsive">
      </a>
    </div>
    

    你可以看到图像的尺寸(取自URL)在这个例子中是800px乘500px,但图像仍然看起来正确缩放 .

    如果您不希望将 padding 应用于容器,请从 .container 中删除并将 max-height 调整为 100%; .

  • 0

    通过降低图像高度来调整div高度!请遵循此代码

    .container {
      border: 1px solid #000;
      height: 250px;
      display: block;
      overflow-y: scroll;
    }
    
    .container p {
      word-wrap: break-word;
    }
    
    <div class='container'>
      <p>This is random information, the height could be differnet depened on the content of the paragraph This is random information, the height could be differnet depened on the content of the paragraph</p>
      <a href='http://google.ca'>
        <img src="http://lorempixel.com/300/170/nature/">
      </a>
    </div>
    

相关问题