问题
I'm trying to set the size (both width and height) of a div to match it's background image size, but I can't get it working. The background image size has to be in percentages, because I'm dealing with a responsive website. On smaller screens, the background should be displayed completely (with less width, but still proportional), and the div who has the image should follow that size.
I tried various values of the background-size, such as auto 100%, cover, contain, etc. but nothing did the trick. There's a similar question here about this: scale div to background image size but it didn't solve my problem either.
I'd really appreciate if someone knows how to do it.
EDIT: I made a fiddle to show the behavior: http://jsfiddle.net/osv1v9re/5/ This line is what is making the background image so small:
background-size: auto 100%;
But if it is removed is removed, the background will fill the proper width, but not the height.
回答1:
tag cannot adapt to background-image size, you need to use an tag and choose between height: auto for the div or javascript
// **** Problem ****
// Wrong html :
<div class="my_class"><div>
// with css :
.my_class {
width: 100%;
height: 100%;
background-image: url(/images/my-image.jpg);
background-size: 100%;
background-position: center;
background-repeat: no-repeat;
}
//**** Solution ****
// use css:
.my_class {
width: 100%;
height: 100%;
background-image: url(/images/my-image.jpg);
background-size: contain;
}
回答2:
*{
padding: 0;
margin: 0;
}
div{
width: 100%;
}
div figure{
padding-top: 36.56%; /* 702px/1920px = 0.3656 */
display: block;
background: url("https://st.fl.ru/images/landing/bg2.jpg") no-repeat center top;
background-size: cover;
}
<div>
<figure></figure>
</div>
回答3:
you can have a responsive height using the padding-bottom or padding-top because you can't fix an height property in '%' with a width in '%'.
div{
background-image: url(url);
background-repeat: no-repeat;
background-size: 100% 100%;
background-position: center;
margin: 0 auto;
width: 100%;
padding-bottom: heightPicure / widthPicture + %; //do it manually or using scss rules
}
回答4:
If you want to make height
proportional to width
and set background-image
this will do the job. There is an easy solution without using JavaScript. Just add <svg>
with specific proportions inside a container.
You must use image dimensions as viewBox <svg viewBox="0 0 960 628"></svg>
Example:
div{
background-image:url('https://cdn.pixabay.com/photo/2018/06/30/09/31/background-image-3507320_960_720.jpg');
background-size:cover;
background-position:50%;
background-repeat:no-repeat;
}
svg{
width:100%;
display:block;
visibility:hidden;
}
.demo-1{width:100%}
.demo-2{width:40%}
<div class="demo-1">
<svg viewBox="0 0 960 628"></svg>
</div>
<hr>
<div class="demo-2">
<svg viewBox="0 0 960 628"></svg>
</div>
来源:https://stackoverflow.com/questions/30319743/fit-div-size-to-background-image