【问题标题】:How to have div fill width and height of browser window and not have the image be stretched如何让 div 填充浏览器窗口的宽度和高度而不拉伸图像
【发布时间】:2018-09-17 15:43:02
【问题描述】:

我正在尝试在浏览器高度和宽度填充 div 中使用图像,并希望图像缩放以适应,它目前正在拉伸。我想像您通常使用背景图像一样使用图像。在这种情况下我不能,因为它使用其 HTML ID 进行切换

我的 CSS

    .cover{
    position: relative;
    background-repeat: no-repeat;
    width: 100%;
    height: 100%;
    display:block; 
    margin: 0 auto;
 }

我的 HTML

<div class="cover" id="1">
    <img class="cover" src="Images/Articles/Index/MRD%2008-041.jpg">


   <a href="Articles/boy.html"> 
   <span class="title">The Next Generation of Film<br>is in Our Own Backyard</span></a>

   <span class="post"> North Toronto sees yet another high budget Disney movie Filmed on     it's grounds.</span>
 </div>

和一个好的 jsfiddle measure。再次,如何使图像填充浏览器窗口的高度和宽度而不拉伸图像?谢谢

【问题讨论】:

  • 你看起来像这样吗? jsfiddle.net/W925K/3
  • i cant in this case because it switches using its html ID 如果类保持不变,为什么不直接使用呢?

标签: html css


【解决方案1】:

使用 background-image 通过 CSS 显示您的图像,并应用额外的属性 background-size 使其填充容器。

这是fiddle

HTML

<div class="cover" id="1">
    <a href="Articles/boy.html"> 
       <span class="title">The Next Generation of Film<br>is in Our Own Backyard</span>
   </a>
</div>

CSS

// Required to allow the .cover container to fill the entire window. min-height could do the trick too depending on your wishes
html,
body {
    width: 100%;
    height: 100%;
    margin: 0;
}

.cover {
    position: relative;
    width: 100%;
    height: 100%;
    display: block;
    background: url('http://placehold.it/550x300') no-repeat center center;
    background-size: cover;
}

【讨论】:

  • 成功了,有什么办法可以在html中引用图像吗?
  • 你为什么要这样做?你可以这样做,但是你需要 JavaScript 来使图像适合,然后你的布局就会受到一些限制。
【解决方案2】:

我建议你使用background-image 而不是&lt;img&gt; 标签。

&lt;img&gt; 不是动态大小图像的好选择,CSS 做得更好。

背景尺寸

CSS3 支持 background-sizecovercontain 的两个新值。

来自MDN background-size

封面

该关键字指定背景图片在保证两个尺寸都大于或等于背景定位区域对应尺寸的情况下,应尽可能缩小。

包含

该关键字指定背景图片在保证两个尺寸都小于或等于背景定位区域对应尺寸的情况下,尽可能的放大。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2015-03-23
    相关资源
    最近更新 更多