前端杂货铺

CSS让背景图片居中显示的方法

2017-02-28  本文已影响1828人  罂粟1995

当我们的背景图片写成:

background: url("images/titleborder.png") no-repeat;

时,表示背景图片不重复,位置会默认为在div中居于左上角。
例:

<html>  
    <head>  
        <meta charset="utf-8" />  
        <title></title>  
        <style type="text/css">  
            #header {  
                width: 100%;  
                height: 400px;  
                border: 1px solid;  
                background: url("images/titleborder.png") no-repeat;  
            }  
        </style>    
    </head>  
    <body>  
        <div id="header">  
              
        </div>  
    </body>  
</html> 

效果:

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;

效果:

![LU6VT_}I]Z3MNA5EQ4442CB.png](https://img.haomeiwen.com/i4853241/69e740d38d342d23.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

令背景图片居于右上角的写法:

background: url("images/titleborder.png") right top no-repeat;

效果:

![S}58~7R6T6E1LBF[]D$)]JM.png](https://img.haomeiwen.com/i4853241/11026cf9df09c476.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

左居中:

background: url("images/titleborder.png") left center no-repeat;
P9_3E4$9[Q4F0EL}9%]R32A.png
上一篇 下一篇

猜你喜欢

热点阅读