我希望背景图片在移动视图中能够响应。
我用它来将背景图像缩放到整个桌面:
html {
background:url("image/2.jpg") no-repeat center center fixed;
background-size: cover;
}
但是我无法取得很好的结果:(这是我的搜索中要求最多的建议)
@media only screen and (max-width: 600px) {
html{
width: 100%;
}
}
中发生的情况
答案 0 :(得分:2)
您可以添加以下内容:
.yourelement {
background-image: url("https://i.stack.imgur.com/viNrB.png");
background-repeat:no-repeat;
background-size:contain;
background-position:center;
height: 247px;
/*Additional code (don't bother adding this):*/
text-align: center;
color: white;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="yourelement">Your content goes in here</div>
</div>
</div>
</div>
您也可以将contain
替换为cover
,但需要添加更多代码。我为此找到的东西:
.ratio4-3 {
width: 100%;
background-image: url("https://i.stack.imgur.com/viNrB.png");
background-size: cover;
height: 0;
padding: 0; /* reset */
padding-bottom: calc(100% * 3 / 4);
}
.text-center {
text-align: center;
color: white;
}
<div class="ratio4-3">
<div class="text-center">
content could go in here
</div>
</div>
答案 1 :(得分:2)
Ciao
一种优雅的解决方案是更好地控制要以横向和纵向模式显示的内容。如果您想对人像屏幕上的风景图像做出响应,则必须按照@salff注释“丢东西”
我的代码段更加灵活,具体取决于用户屏幕:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html
{
background:url("https://www.hotelmedici.com/images/slide_home/11_Fori_imperiali_1600X917.jpg") no-repeat center center fixed;
background-size: cover;
width: 100%;
}
#warning-message { display: none; }
@media only screen and (orientation:portrait)
{
#wrapper { display:none; }
#warning-message { display:block; color: white;}
html
{
background:url("https://s3files.core77.com/blog/images/2013/11/ESB-HalloweenLightShow-1.jpg") no-repeat center center fixed;
background-size: cover;
height: 100%;
}
}
</style>
</head>
<body>
<div id="wrapper">
<h2>Responsive Images</h2>
<p>If you want the image to scale both up and down on responsiveness, set the CSS width property to 100% and height to auto.</p>
<p>Resize the browser window to see the effect.</p>
</div>
<div id="warning-message">
this website is only viewable in landscape mode
</div>
</body>
</html>
注意:该代码是通过交叉调整代码w3schools snippet和this answer
希望这会有所帮助,周末愉快,
安东尼诺