我想在我的网站中添加一个背景图像,该div应该在所有设备上完美调整大小。我尝试了最简单的方法,比如“身高:100%”,但根本不起作用。我也尝试了媒体查询,当然这些查询很有用,但是相当复杂,所以我想问问是否有更简单的方法来解决这个问题。如何根据屏幕尺寸缩放div中的背景图像
这里的HTML
<div class="bg"></div>
这就是今天的CSS
.bg {
background: url('bg.jpg') no-repeat center cover;
}
我想在我的网站中添加一个背景图像,该div应该在所有设备上完美调整大小。我尝试了最简单的方法,比如“身高:100%”,但根本不起作用。我也尝试了媒体查询,当然这些查询很有用,但是相当复杂,所以我想问问是否有更简单的方法来解决这个问题。如何根据屏幕尺寸缩放div中的背景图像
这里的HTML
<div class="bg"></div>
这就是今天的CSS
.bg {
background: url('bg.jpg') no-repeat center cover;
}
@Sqnkov有正确的答案。一个空白的div将与设置。
尝试运行下面的代码并参阅。 (制作完整页面并调整浏览器大小)。 center center
以Y轴和X轴为中心。 background-size: cover;
使图像覆盖所有可用空间。如果你想确保整个图像在视图中,请改用background-size: contain;
。
body{
margin: 0; /* Stripping out margin and padding so .bg can be full width*/
padding: 0;
}
.bg {
box-sizing: border-box; /*Not necessary in this situation*/
display: block; /*Not necessary, but we do want it this way*/
width: 100vw; /*Not necessary, but we do want it this way*/
height: 100vh; /*Necessary. 100vh = 100% of the viewport height*/
padding: 0; /* No padding */
margin: 0; /* No margins */
background: url('https://images6.alphacoders.com/405/405948.jpg') no-repeat center center;
/* Shorthand: image, repeat, X align, Y align. */
background-size: cover; /* Cover all available space*/
}
<div class="bg"></div>
或者,如果指定的父容器(html, body
)的高度和宽度为100%则可以使用100%
高度/宽度,而不是100vh/vw
子.bg
容器上如百分数均以相对于父容器。
请参见下面的例子: '?在所有设备上完美地调整'
html, body{
margin: 0; /* Stripping out margin and padding so .bg can be full width*/
padding: 0;
width: 100%; /*Setting parent width -- child width is relative*/
height: 100%; /*Setting parent height -- child height is relative*/
}
.bg {
box-sizing: border-box; /*Not necessary in this situation*/
display: block; /*Not necessary, but we do want it this way*/
width: 100%;
height: 100%; /* Now 100% height will work */
padding: 0; /* No padding */
margin: 0; /* No margins */
background: url('https://images6.alphacoders.com/405/405948.jpg') no-repeat center center;
/* Shorthand: image, repeat, X align, Y align. */
background-size: cover; /* Cover all available space*/
}
<div class="bg"></div>
非常感谢! – Timo
没问题!当你可以运行它时,更容易想象它:D我真的很喜欢,所以让我们嵌入代码片段。无论如何,如果这回答了您的问题,您可以将此标记为已接受答案* wink-wink *; p – StephanieQ
我还在学习自己,但你尝试过 “背景大小:覆盖;”在你的CSS?
查看更多的信息在这里:https://www.w3schools.com/cssref/css3_pr_background-size.asp。
只需将大小首选项应用于背景属性。下面是一个速记用法:
这是充满其父到边框的大背景图像的设置。
background: url('images/image.jpg') no-repeat center center/cover;
等于:
background-image: url('images/image.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
我建议给this MDN thread读。
你什么意思 - 设备具有不同的宽高比。 – sol
是的,这是重点。是不是有一种简单的方法让背景图像调整自己独立于设备的屏幕大小? – Timo
我会详细说明...您如何让横向照片以纵向模式在移动设备上进行观看?你想要它覆盖整个屏幕并居中? – sol