简体   繁体   English

根据宽度缩放背景图像的高度

[英]Scale Background Image Height Based on Width

I'm trying to set up a section with a background image with the width of the entirety of the page, and the height scaled based on the width. 我正在尝试使用背景图像来设置一个部分,该背景图像的页面宽度为整个页面,高度根据宽度缩放。

I tried setting background-size: cover , but that didn't make any difference — the height of the background image stayed as the height of the content of the section. 我尝试设置background-size: cover ,但是没有任何区别-背景图像的高度保持为该部分内容的高度。

You can set contain, cover and percent height 您可以设置包含,覆盖和高度百分比

.backgroundCover {
      background-image: url(http://www.messletters.info/animated-backgrounds/71animatedbg.gif);
        background-size: cover;
}

.backgroundContain {
      background-image: url(http://www.messletters.info/animated-backgrounds/71animatedbg.gif);
        background-size: contain;
}
.backgroundPercents{
   background-image: url(http://www.messletters.info/animated-backgrounds/71animatedbg.gif);
        background-size: 100% 100%; 
}

See JSFiddle 参见JSFiddle

You might want to look at background-size: contain; 您可能需要查看background-size: contain;

To quote W3schools, contain achieves the following: 引用W3schools, 包含可达到以下目的:

Scale the image to the largest size such that both its width and its height can fit inside the content area 将图像缩放到最大尺寸,以使其宽度和高度都适合内容区域

Use contain 使用包含

background-size: contain;

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area. 此关键字指定背景图像应缩放为尽可能大,同时确保其尺寸均小于或等于背景定位区域的相应尺寸。

Try this: http://jsfiddle.net/fX5E8/ . 试试这个: http : //jsfiddle.net/fX5E8/

HTML: HTML:

<div></div>

CSS: CSS:

div {
    height: 500px;
    outline: 1px solid red;
    background: url(http://placehold.it/500x200/cccccc&text=Howdy)
                no-repeat
                0% 0%/100%;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM