編碼的世界 / 優質文選 / 生涯

CSS讓背景圖片居中顯示的方法


2022年4月21日
-   

當我們的背景圖片寫成:
background: url("images/titleborder.png") no-repeat;
時,表示背景圖片不重複,位置會默認為在div中居於左上角。
例:
#header {
width: 100%;
height: 400px;
border: 1px solid;
background: url("images/titleborder.png") no-repeat;
}
效果:

1.png
如果背景圖片寫成:
background: url("images/titleborder.png") center center no-repeat;
效果是水平垂直居中對齊:

2.png
第一個center表示水平居中,第二個center表示垂直居中。
要令背景圖片水平居中,並貼近div頂部,代碼可以這麼寫:
background: url("images/titleborder.png") center 0 no-repeat;
或者:
background: url("images/titleborder.png") center top no-repeat;
效果:
令背景圖片居於右上角的寫法:
background: url("images/titleborder.png") right top no-repeat;
效果:
左居中:
background: url("images/titleborder.png") left center no-repeat;

P9_3E4$9[Q4F0EL}9%]R32A.png

熱門文章