Fit div size to background image

若如初见. 提交于 2019-11-29 12:29:38

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;
}

*{
    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>

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!