Fit div size to background image

后端 未结 3 957
你的背包
你的背包 2020-12-03 23:41

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 percen

相关标签:
3条回答
  • 2020-12-04 00:26

    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;
    }
    
    0 讨论(0)
  • 2020-12-04 00:29

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

    0 讨论(0)
  • 2020-12-04 00:34

    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
    
    }

    0 讨论(0)
提交回复
热议问题