首页 文章

无论图像宽高比如何,都可以制作背景图像填充div

提问于
浏览
2

我想知道如何用图像填充 div 的背景 . 无论图像的宽高比(风景或肖像)如何 . 我试过用几种方法 . 超过 background-size: cover;background-size: 100% 100%; 它并不总是填满div . div具有横向宽/高比,图像具有随机比率 . 如果我尝试 background-size: cover; ,景观将填满整个背景,但肖像不会(他们在左侧和右侧有间隙) .

编辑:

div { 
   background: url(img.png) no-repeat center center; 
   background-size: cover; 
   height: 100%; 
   width: 100%;
}

enter image description here

2 回答

  • 1

    background-size:cover; 应该可以满足您的需求 . 基本上, cover 值将使背景图像完全填充div,无论div的方向或大小如何,同时保持图像的纵横比 . 这个解决方案的一个警告是图像将被裁剪,因为它必须拉伸以填充div .

    More info on the background-size property

  • 1

    你可以试试这个

    div { 
       background: url(img.png) no-repeat center center; 
       background-size: contain; /*i think its better to use contain if you;re using a large png*/
       height: 100vh!important; 
       width: 100hw!important;
       overflow:visible;
    }
    

相关问题