有没有办法将背景大小设置为包含和覆盖?
Is there anyway to set background-size to both contain and cover?
这是我尝试的笔 https://codepen.io/alexyap/pen/VbvGvw
<div id="bg">
</div>
* {
margin: 0;
padding: 0;
}
#bg {
background: url('https://static.pexels.com/photos/198747/pexels-photo-198747.jpeg');
height: 60vh;
width: 100%;
background-repeat: no-repeat;
background-size: 100vw;
}
我几乎已经弄清楚了,但我似乎无法复制这个网站 https://sierradesigns.com/ 是如何做到的(检查登录页面上的滑块图像),无论值是多少,我的底部都被切断了我给身高
通过将背景大小设置为 cover
,您授予浏览器调整图像直到完全覆盖该区域的特权;它会忽略您指定的宽度和高度值。
使用contain
你可以让浏览器决定如何调整图像,使整个图像适合区域,这可能是基于高度或宽度来完成这个(取决于方向图片宽或高)。
background-size: 100% 100%
可能是您要查找的内容,但这会不成比例地调整图像(即:根据方向拉伸或压缩)。但是,当您说 "both cover and contain".
时,这听起来确实是您想要的
有很多方法可以放置和缩放用作背景的图像(其中背景不一定表示 CSS 背景 属性)
下面是我如何完成此操作的简化示例(假设图像大约为 700x300 像素)
.container-wrap {
width:100%;
}
.container {
position:relative;
padding:42.86% 0 0 0;
/* where padding = the proportion of the images width and height
which you can get by division: height / width = 0.42857 */
}
.container img {
position:absolute;
top:0px;
right:0px;
bottom:0px;
left:0px;
}
重要的是您的图像彼此保持紧密的比例——如果它们稍微偏离,对于大多数图像,大多数人应该不会看到轻微的失真
同样,还有其他方法可以做到这一点。您链接到的网站应用了类似的概念。概念相同,方法略有不同(例如他们在图像上使用 width:100% 而不是绝对定位),其中概念 = "using some sort of method to proportion the images to the container so it will magically scale"
请注意,同样的方法可以应用于视频容器(例如来自 YouTube)。
您 link 的页面保持容器的纵横比不变。
您可以同时使用宽度和高度的 vw 单位来获得此效果(例如)
#bg {
background: url('http://lorempixel.com/1000/600/');
height: 30vw;
width: 50vw;
background-size: cover;
}
<div id="bg">
</div>
这是我尝试的笔 https://codepen.io/alexyap/pen/VbvGvw
<div id="bg">
</div>
* {
margin: 0;
padding: 0;
}
#bg {
background: url('https://static.pexels.com/photos/198747/pexels-photo-198747.jpeg');
height: 60vh;
width: 100%;
background-repeat: no-repeat;
background-size: 100vw;
}
我几乎已经弄清楚了,但我似乎无法复制这个网站 https://sierradesigns.com/ 是如何做到的(检查登录页面上的滑块图像),无论值是多少,我的底部都被切断了我给身高
通过将背景大小设置为 cover
,您授予浏览器调整图像直到完全覆盖该区域的特权;它会忽略您指定的宽度和高度值。
使用contain
你可以让浏览器决定如何调整图像,使整个图像适合区域,这可能是基于高度或宽度来完成这个(取决于方向图片宽或高)。
background-size: 100% 100%
可能是您要查找的内容,但这会不成比例地调整图像(即:根据方向拉伸或压缩)。但是,当您说 "both cover and contain".
有很多方法可以放置和缩放用作背景的图像(其中背景不一定表示 CSS 背景 属性)
下面是我如何完成此操作的简化示例(假设图像大约为 700x300 像素)
.container-wrap {
width:100%;
}
.container {
position:relative;
padding:42.86% 0 0 0;
/* where padding = the proportion of the images width and height
which you can get by division: height / width = 0.42857 */
}
.container img {
position:absolute;
top:0px;
right:0px;
bottom:0px;
left:0px;
}
重要的是您的图像彼此保持紧密的比例——如果它们稍微偏离,对于大多数图像,大多数人应该不会看到轻微的失真
同样,还有其他方法可以做到这一点。您链接到的网站应用了类似的概念。概念相同,方法略有不同(例如他们在图像上使用 width:100% 而不是绝对定位),其中概念 = "using some sort of method to proportion the images to the container so it will magically scale"
请注意,同样的方法可以应用于视频容器(例如来自 YouTube)。
您 link 的页面保持容器的纵横比不变。
您可以同时使用宽度和高度的 vw 单位来获得此效果(例如)
#bg {
background: url('http://lorempixel.com/1000/600/');
height: 30vw;
width: 50vw;
background-size: cover;
}
<div id="bg">
</div>