h1标签前后的css背景图片

时间:2013-06-26 13:58:24

标签: css

我必须将所有h1标签设置为在h1文本之前和之后都有图像。

我之前知道如何添加图片,但不知道如何添加图片。

CSS(样式h1在文本之前有图像)

h1 {
        background-image: url('images/h_ltr.png');
        background-position: left center;
        background-repeat: no-repeat;
        text-align: center;
        font-size: 22px;
        font-weight: bold;
        color: #5d5d5d;
    }

3 个答案:

答案 0 :(得分:12)

您可以使用:before:after css选择器。

h1:before {
    background-color: green;
    padding: 0 20px;
    content: " ";
}
h1:after {
    background-color: red;
    padding: 0 20px;
    content: " ";
}
<h1>Test</h1>

答案 1 :(得分:2)

您还可以使用多个背景图像。在此示例中,我为左,中和右bg图像设置了背景图像:

h1, h2, h3, h4, h5, h6 {
    background-image: url("images/heading-bg-left.png"), url("images/heading-bg-right.png"), url("images/heading-bg-center.png"); /* set each bg image */
    background-position: left center, center center, right center; /* set position of each bg image */
    background-repeat: no-repeat, no-repeat, repeat-x; /* set repeat of each bg image */
    padding: 0 92px; /* 92px is the width of my left and right bg images */
    height: 120px; /* 120px is the height of each bg image */
    line-height: 120px; /* ditto */
}

代码相当不言自明,但基本上我使用了三个background-image,其中包含三个background-position和三个background-repeat

请注意,图像的渲染顺序相反。因此,在我的示例中,左右图像将绘制在中心图像的顶部。

答案 2 :(得分:0)

<style>
.container{
    width:900px;
    margin:0 auto;
    position:relative;
    overflow:hidden;
    text-align:center;
}
h1{
    font-size:20px;
    display:inline-block;
    position:relative;
    padding:0 40px;
}
h1:after{
    height:1px;
    position:absolute;
    content:"";
    background:green;
    top:10px;
    width:500%;
    right:-500%;
}
h1:before{
    height:1px;
    position:absolute;
    content:"";
    background:red;
    top:10px;
    width:500%;
    left:-500%;
}


</style>

<div class="container">
     <h1>1</h1>
</div>
相关问题