div 由 css 背景图像生成的响应图像
Responsive image with div by css background-image
我发现这里也有类似的问题,比如Responsive CSS background images。
这个解决方案对我不起作用,除非我已经为 div 设置了图像的确切高度。首先,如果我不设置它的高度,图像将不会显示,因为 div 的高度将为零。其次,如果我为它设置高度,它不会响应浏览器宽度。就像我加宽浏览器一样,我希望图像会相应地放大以适应宽度。但是如果我使用 height:100%,图像将不会再次显示。
我希望它是:当我调整浏览器宽度时,图像宽度和高度将通过使用 css background-image 属性响应地缩放 up/down。
我想这与一些基本的 css 技巧有关,但我并不是很擅长。谁能建议我一些解决方案?非常感谢!
.top-banner{
height:100%;
}
@media (min-width:768px) {
.top-banner {
background-image: url('http://everetttheatre.com/wp-content/uploads/2016/03/toy-story-banner.jpg');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
}
}
@media (max-width:767px) {
.top-banner {
background-image: url('https://i.pinimg.com/originals/31/de/36/31de3624c128d5748039ae9523223eb5.jpg');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
}
}
<div class="top-banner">
</div>
百分比高度将不起作用,除非任何父元素具有像素高度。
我的建议是使用 img 标签而不是 background-image 使其响应。
但是如果您只能将 div 与背景图像一起使用,那么您已经使用 javascript 在 window 调整大小事件中更改了 div 的高度。
如果图像是 4:3 比例,代码将如下所示:
<body onresize="resizeFunction()">
<style>
.imgBackground {
width : 100%;
background : your image link;
background-size : 100%;
}
</style>
<div class="imgBackground"></div>
<script>
function resizeFunction() {
var widthOfDiv = $('.imgBackground').width();
var heightOfDiv = width/1.33;
$('.imgBackground').height(heightOfDiv);
}
</script>
</body>
我发现这里也有类似的问题,比如Responsive CSS background images。
这个解决方案对我不起作用,除非我已经为 div 设置了图像的确切高度。首先,如果我不设置它的高度,图像将不会显示,因为 div 的高度将为零。其次,如果我为它设置高度,它不会响应浏览器宽度。就像我加宽浏览器一样,我希望图像会相应地放大以适应宽度。但是如果我使用 height:100%,图像将不会再次显示。
我希望它是:当我调整浏览器宽度时,图像宽度和高度将通过使用 css background-image 属性响应地缩放 up/down。
我想这与一些基本的 css 技巧有关,但我并不是很擅长。谁能建议我一些解决方案?非常感谢!
.top-banner{
height:100%;
}
@media (min-width:768px) {
.top-banner {
background-image: url('http://everetttheatre.com/wp-content/uploads/2016/03/toy-story-banner.jpg');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
}
}
@media (max-width:767px) {
.top-banner {
background-image: url('https://i.pinimg.com/originals/31/de/36/31de3624c128d5748039ae9523223eb5.jpg');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
}
}
<div class="top-banner">
</div>
百分比高度将不起作用,除非任何父元素具有像素高度。
我的建议是使用 img 标签而不是 background-image 使其响应。
但是如果您只能将 div 与背景图像一起使用,那么您已经使用 javascript 在 window 调整大小事件中更改了 div 的高度。
如果图像是 4:3 比例,代码将如下所示:
<body onresize="resizeFunction()">
<style>
.imgBackground {
width : 100%;
background : your image link;
background-size : 100%;
}
</style>
<div class="imgBackground"></div>
<script>
function resizeFunction() {
var widthOfDiv = $('.imgBackground').width();
var heightOfDiv = width/1.33;
$('.imgBackground').height(heightOfDiv);
}
</script>
</body>