【问题标题】:Why the parent div still keeps the width of its child image original width?为什么父 div 仍然保持其子图像原始宽度的宽度?
【发布时间】:2015-07-23 06:58:23
【问题描述】:

我有几个 div 和这样的图像

<div class="show-image">
    <div class="image-info-box">
        <div class="info-content">test</div>
    </div>
    <div class="image-container">
        <img class="img-box" src="image.png" />
    </div>
</div>

css文件是:

.show-image {
    display: inline-block;
    vertical-align: top;
}

.img-box {
    padding-top: 30px;
    width: 75%;
    text-align: center;
    display: block;
}

.image-container {
    display: inline-block;
    white-space: nowrap;
    width: auto;
}

.image-info-box {
    width: 100%;
    padding-top: 30px;
    text-align: center;
}

.info-content {
    float: center;
}

我希望图像具有 75% 的宽度,因此我将 img-box 类的宽度设置为 75%(例如图像宽度为 1008px,因此 img-box 的宽度为 756px)。问题是为什么具有类 image-container 的 div 仍然保持原始图像宽度,即示例中的 1008px。图像容器如何适应 img-box 的宽度?

【问题讨论】:

  • div 默认是块元素,默认情况下,width: 100%; 是所有块元素。基本 CSS 行为。
  • 那么如何设置父 div 适合子图像宽度?

标签: html css image


【解决方案1】:

将限制宽度应用于父级,而不是子级。这样它就可以按您的预期工作。

.image-container {
display: inline-block;  
width:75%;
}

.image-info-box {
width: 100%;
padding-top: 30px;
text-align: center;
}

DEMO

【讨论】:

  • 是的,它适用于图像容器 div,但显示图像 div,即根 div,仍然是原始宽度,即使我将其宽度设置为 75%。
【解决方案2】:

只使用 div(没有图像标签)你可以这样做。

<div class="show-image">
    <div class="image-info-box">
        <div class="info-content">test</div>
    </div>
    <div class="image-container">
    </div>
</div>

使用这个 CSS。

.image-container {
    display: inline-block;
    white-space: nowrap;
    width: auto;
    background: url('Hopetoun_falls.jpg') no-repeat;
    width: 500px;
    height: 500px;
    background-size: 100%;
}

【讨论】:

    猜你喜欢
    • 2012-12-13
    • 2014-09-05
    • 2011-03-28
    • 2016-03-02
    • 2021-02-09
    • 2013-03-29
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多