如何在<h1> </h1>中使用图像和重复背景

时间:2014-08-18 19:06:08

标签: html css

我尝试创建一个文本居中的<h1>,每边都有一个图像,然后动态填充容器的剩余宽度。

我尝试过一些技巧......目前使用:before和:after,嵌套跨度。 :工作之后,但试图解决:部分之前。

小提琴:jsfiddle.net/dtar4rgs/

2 个答案:

答案 0 :(得分:1)

您可以使用flex来实现您的目标(demo (supports flexbox)demo (doesn't support flexbox)):

<div id="container">
    <h1><span>a b c</span></h1>
    <p>Change text shorter or longer.</p>
    <p>Need left lines to be dynamic.</p>
</div>
h1 {
    display:flex; /* Treats the :before, :after, and span as individual items */
    align-items:center; /* Aligns items vertically (to align border properly) */
    text-align:center; /* Aligns items horizontally for browsers that don't support flexbox */
}
h1 span {
    /* Places arrow on each side of span */
    background: url('https://dl.dropboxusercontent.com/u/101534624/arrow_cyan.gif') no-repeat left,
    url('https://dl.dropboxusercontent.com/u/101534624/arrow_cyan.gif') no-repeat right;
    padding: 0 50px; /* Prevents text from overlapping image */
}
h1:before,
h1:after {
    content: " ";
    /* Lines on sides of header */
    background: url('https://dl.dropboxusercontent.com/u/101534624/h1-lines.png') repeat-x;
    height: 6px; /* Height of lines */
    flex-grow:1; /* Makes lines expand to edges of screen */
}

注意: Support for flexbox缺少(IE11 +),但text-align:center,唯一的区别是缺少行。

答案 1 :(得分:0)

嗯,这让你分道扬..我不确定你想要的两个<p>元素是什么,但我会说100%的不良做法和非赛门铁克将它们放在<h*>中。

以下是代码:Fiddle

我已经在那里放了另一个嵌套的span来为你提供所需的白色缓冲区,这对于背景图像效果不佳。所以它可能不是你想要的。这样,您的<h1>可以是任意文字长度。

HTML:

<div id="container">
    <h1><span><span>Heading</span></span></h1>
</div>
<p>Change text shorter or longer.</p>
<p>Need left lines to be dynamic.</p>

CSS:

 #container {
    width: 1000px;
    border: 1px solid #eee;
    background: url('https://dl.dropboxusercontent.com/u/101534624/h1-lines.png') repeat-x center;
}
h1 {
    text-align: center;
    position: relative;
    overflow: hidden;
}
h1 span {
    background-color: #fff;
    padding: 0 10px;
}
h1 span > span {
    background: url('https://dl.dropboxusercontent.com/u/101534624/arrow_cyan.gif') no-repeat left, url('https://dl.dropboxusercontent.com/u/101534624/arrow_cyan.gif') no-repeat right;
    padding: 0 50px;
}