【问题标题】:Image makes fix sized div larger图像使固定大小的 div 更大
【发布时间】:2015-10-12 06:57:46
【问题描述】:

我正在尝试将图像放入我的网站。 该图像位于具有固定大小的 div 中。 问题是图像拉伸了整个 div 当我在 CSS 中使用自动高度时。

图像适合其 div,将其高度和宽度设置为 100%:

现在我想保持图像未拉伸。 所以我将宽度设置为 100%,将高度设置为 auto 正如它所描述的here 将图像设置在下面部分下的图层中后 但在页面的下一部分有图层。

这是我使用的 HTML 代码:

<div class="section4">
        <section class="half">
            <div class="officePicContainer">
                <img src="officePic.jpg" alt="New Office of MEGO" class="officePic">
            </div>
        </section>

        <section class="half">


        </section>  
    </div>

以及 CSS 代码:

 .half {
    height: 50%;
    position: relative;
}

.half:first-child {


}
.half:last-child {
    background: #950049;

}
     .officePic {
        height: auto;
        width: 100%;
    }

如何在不拉伸图像的情况下调整图像大小并使其适合其父 div?在 CSS 中还有可能吗?还是需要Java Script?

感谢您的帮助!

【问题讨论】:

    标签: html css image resize


    【解决方案1】:

    创建 div 和 background-size:cover css 标签并设置位置:fixed

    <div class="demo" style="background-image:url(example.png);background-size: cover; background-position:center center;"></div>
    

    【讨论】:

    • 等等..我做错了。你的解决方案对我来说很好。谢谢!
    • 如果没有JS,你必须给div一个固定的高度,并且图像不会被拉伸。
    • 没问题,将我的答案设置为解决方案,以帮助其他有相同问题的人;)
    【解决方案2】:

    &lt;div&gt;&lt;img src="http://www.engineering.com/Portals/0/BlogFiles/swertel/heart-cloud.jpg" width=100% /&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 2014-02-11
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 2015-09-06
      相关资源
      最近更新 更多