html div背景自动居中显示,网站背景图居中自适应以及拉伸填充CSS代码解决方法...
寫這篇水文呢,也是最近在自己在魔改一個(gè)主題用作新做的班級網(wǎng)站。
發(fā)現(xiàn)模版的背景圖片以及其他地方的圖片顯示只能在電腦端看到,而在移動端不能夠自適應(yīng)。順便也整理出來。
首先是圖片的居中自適應(yīng):
需要先給CSS background-repeat 屬性賦值no-repeat,使圖片不重復(fù)只顯示一張。
然后再定位背景圖像位置,給CSS background-position 屬性賦值center,設(shè)置水平和垂直都居中。
接下來就是圖片尺寸了,給background-size屬性賦值,并配合background-position-x和background-position-y賦值center來實(shí)現(xiàn)CSS背景圖片background-image縮放后居中顯示。
而background-size的賦值方法有多種:
1.給background-size屬性賦值容器寬度和高度中的最小值,實(shí)現(xiàn)CSS背景圖片縮放后居中顯示。background-size:400px 200px;
2.給background-size屬性賦值100%實(shí)現(xiàn)CSS背景圖片縮放后居中顯示。(這種賦值方法會導(dǎo)致圖片非等比例縮放,也就是導(dǎo)致圖片會適應(yīng)容器的高寬比。)background-size:100% 100%;
3.通過background-size:contain實(shí)現(xiàn)CSS背景圖片縮放后居中顯示。(contain的優(yōu)點(diǎn)是會保留背景圖片的寬高比,不會被拉伸變形,所以適用于保留背景圖片寬高比的需求中。)background-size:contain;
因?yàn)閳D片尺寸與容器大小不一樣,所以我們采用第二個(gè)百分比適應(yīng)的方法。
所以最終代碼如下:body {
background-image: url(https://img.lkxin.cn/*****);
width:***px;
margin:**px auto -**px auto;
text-align: center;
padding:**px;
background-repeat: no-repeat;
background-position-x: center;
background-position-y: center;
background-size: 100% 100%;
color:#FFFFFF;
}
接下來是背景圖以拉伸方式(不重復(fù))填充背景
方法同上,同樣利用background-repeat: no-repeat;和background-size: 100% 100%。
而不同的地方是上面使用的background-position屬性的作用是定位,而接下來要用到background-attachment屬性的作用是將其固定住,使其不滾動,不移位置。
那么就需要給background-attachment賦值fixed。background-attachment: fixed;
最終代碼為:background-image: url(https://img.lkxin.cn/*****);
background-attachment: fixed;
background-repeat: no-repeat;
background-size: 100% 100%;
OK!文章結(jié)束.......
贊 0
原創(chuàng)文章,作者:清酒,如若轉(zhuǎn)載,請注明出處:https://blog.lkxin.cn/archives/344.html
總結(jié)
以上是生活随笔為你收集整理的html div背景自动居中显示,网站背景图居中自适应以及拉伸填充CSS代码解决方法...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QEMU 模拟器(一)
- 下一篇: 鼠标计算机,事实:计算机鼠标在哪里?