美文网首页前端杂货铺
CSS让背景图片居中显示的方法

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

作者: 罂粟1995 | 来源:发表于2017-02-28 17:20 被阅读1828次

当我们的背景图片写成:

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

相关文章

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

    当我们的背景图片写成: 时,表示背景图片不重复,位置会默认为在div中居于左上角。例: 效果: 如果背景图片写成:...

  • table的运用

    如何使多个不同比例的图片,上下水平居中 方法一: 给 a 标签设置背景图片 CSS样式: HTML: 方法二...

  • CSS总结一

    一、背景图片占屏幕的全屏 二、使用flex布局让文字垂直居中 1:html 2:css 三、css分列多行 父元素...

  • Css让div在屏幕上居中

    # 让div在屏幕上居中(水平居中+垂直居中)的方法总结 - html代码如下: - Css居中方法 (敲黑板)...

  • 多行文字垂直居中显示

    单行文字居中显示:line-height html: css: 多行文字居中显示: html: css: 给父元素...

  • css第三节

    CSS装修学习在css的div里写text-align可以调整文本框内容显示方法,center是居中显示。在文本显...

  • CSS - 垂直水平居中方法

    前言 总括:整理 css 垂直水平居中方法,区分内联元素与块级元素 CSS垂直居中和水平居中 用css让一个容器水...

  • CSS水平垂直居中总结

    CSS水平居中、垂直居中、水平垂直居中方法总结 文字的水平居中: 单行文字的垂直居中: 让有宽度的div水平居中:...

  • 垂直居中显示(文字&块级元素)

    文字在div中垂直居中显示 -方法1:将div改为table格式css如下: html如下: -方法2:将div改...

  • CSS解决盒模型居中的问题

    CSS实现盒子模型水平居中、垂直居中、水平垂直居中的多种方法 CSS实现盒子模型水平居中的方法 全局样式 第一种:...

网友评论

    本文标题:CSS让背景图片居中显示的方法

    本文链接:https://www.haomeiwen.com/subject/xaoxgttx.html