【问题标题】:Absolutely positioned DIV's width not resizing based on child image绝对定位的 DIV 的宽度不根据子图像调整大小
【发布时间】:2014-01-11 03:45:07
【问题描述】:

我有一个绝对定位的 div,其中包含百分比高度和图像。该图像的高度为 100%,宽度为 auto。调整视口高度时,绝对 div 不会调整其宽度,图像要么被截断,要么你会看到 div 的背景。

示例:http://jsfiddle.net/Y5Cr7/

CSS

div {
    position: absolute;
    overflow: hidden;
    height: 50%;
    bottom: 80px;
    left: 5%;
    background: blue;    
}

img {
    height: 100%;
    width: auto;
    display: block;
}

HTML

<p>adjust the height of the viewport</p>

<div>
    <img src="http://lorempixel.com/400/200" />
</div>

【问题讨论】:

标签: html css responsive-design


【解决方案1】:

div 的宽度不会对应于其高度的任何变化,这与 img 不同(此外,div' s 隐式宽度现在对应于视口的宽度)。

我在这里看到两个选项...

  1. 媒体查询
  2. JavaScript

库(例如 jQuery)可能是您最好的选择(这里是 jsfiddle):

$(window).resize(function() {

    var imgWidth = $('img').outerWidth();

    $('div').css({
        'width':imgWidth
    });

});

【讨论】:

  • 我希望避免使用 JS 来解决问题,但这可能是不可能的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-03-29
  • 2011-07-18
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 2015-02-06
  • 1970-01-01
相关资源
最近更新 更多