【问题标题】:How to fit IMG in parent DIV where its height is not set?如何在未设置其高度的父 DIV 中适合 IMAGE?
【发布时间】:2016-09-18 17:42:19
【问题描述】:

我有这种情况:我想制作一个 IMG 高度以适合其没有设置高度的父 DIV。这是示例代码:

.box_NewsList {
  width: 100%;
  background: #ffa;
  overflow: hidden;
  display: inline-block;
}
.box_NewsList>img {
  height: 100%;
  display: inline-block;
}
.box_NewsPreview {
  padding: 15px;
  width: auto;
}
.box_NewsPreview>.tit_News {
  font-size: 1.5rem;
  line-height: 1.5rem;
  position: relative;
  margin: -15px 0 15px;
  padding: 15px 0 0;
  background: transparent url(../imgs/main_menu_hover.png) no-repeat top left;
}
<div class="box_NewsList">
  <img class="pull-left" src="mypicture.jpg">
  <div class="box_NewsPreview">
    <h1 class="tit_News">MyTitle</h1>
    <div class="txt_Abstract">
      <p>Long text abstract here</p>
    </div>
    <button class="btn btn-default btn-rounded pull-right">READ</button>
  </div>
  <div class="clear"></div>
</div>

如何使 img 高度适合具有 box_NewsPreview 类的 div 的高度?

.box_NewsPreview>.txt_Abstract p{color:#7e7e7e;font-family:Roboto, sans-serif;font-size:1rem;font-weight:300;text-align:justify;}

如果我在 box_NewsList 中添加一个高度值,例如 height:300px;,它可以正常工作。

如果我设置了height:autoheight:initialheight:inherit,或者我没有在该类中添加任何高度值,那么我将获得完整大小的 IMG,而不是调整其父高度的大小。

【问题讨论】:

  • 您希望图像如何定位,在文本旁边还是?
  • 接下来是文本。例如,pull-left 类包含 float:left;

标签: html css image height


【解决方案1】:

我认为实现你想要的最简单的方法是使用一点 jQuery。我认为纯 CSS 是不可能的

我举了一个例子,我在.box_NewsList上设置position: relative;,在.box_NewsList&gt;img上设置position: absolute;

还有这个小脚本循环图像并为文本添加填充:

$('.box_NewsList').each(function() {
    var imageWidth = $(this).find('img').width();
  $(this).find('.box_NewsPreview').css('padding-left', imageWidth + 15);
});

Here is a fiddle

【讨论】:

  • 是的,我认为 jQuery 函数是一种方式。这可能是自己的代码: $('.box_NewsList').each(function() { var theHeight = $(this).height(); $(this).find('img').css('height', theHeight+'px'); });我在 CSS 中将 img 高度设置为 0
【解决方案2】:

试试

<div class="box_NewsList">
   <div class="box_NewsPreview">
   <img class="pull-left" src="mypicture.jpg" stretch="fill">
      <h1 class="tit_News">MyTitle</h1>
      <div class="txt_Abstract"><p>Long text abstract here</p></div>
      <button class="btn btn-default btn-rounded pull-right">READ</button>
   </div>
   <div class="clear"></div>
</div>

看起来&lt;img&gt; 在 news_list 而不是 news_preview 中。
我在 img 中添加了拉伸,所以无论如何它总是会拉伸到 div 的大小:)

【讨论】:

  • 这可能不是你想要的,但是是的,那我只是误解了。
  • 我试过了,我也有同样的事情。如果没有高度设置为box_newsPreview,则IMG高度设置为全尺寸。
  • 如果你真的很懒,你可能只需要创建一个函数,如果 div 的高度为 ,将图像的可见性设置为 false
  • 除此之外我不知道为什么图像最大化
  • 当然,我并不懒惰,但如果我能通过 CSS 做到这一点是首选方式。
猜你喜欢
  • 1970-01-01
  • 2019-08-13
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多