【问题标题】:How to make a line before and after my h1 tag?如何在我的 h1 标签之前和之后制作一行?
【发布时间】:2012-02-20 11:21:45
【问题描述】:

我已经四处寻找了一个解决方案,以了解如何制作这样的东西:

----------- 我的文字 -------------- 在 HTML/CSS 中。所以我需要在我的文本前后添加一个 hr 标签。

有人知道如何解决这个问题吗?

【问题讨论】:

标签: html css


【解决方案1】:
<!DOCTYPE html>
<html>
<head>
<title>Inline HR</title>
<style type="text/css">
div {
    text-align: center;
}

hr {
    display: inline-block;
    width: 40%;
}
</style>
</head>
<body>
<div style="center">
<hr>
My Text
<hr>
</div>
</body>
</html>

演示:http://jsfiddle.net/cKrqK/

但是,如果您对 HR 因40% 宽度而没有一直延伸到页面边缘感到不满意,您可以通过以下方式解决。

<!DOCTYPE html>
<html>
<head>
<title>Text on HR</title>
<style type="text/css">
.text {
    position: relative;
    top: -1em;
    text-align: center;
}

.text span {
    background-color: #ffffff;
    margin-left: auto;
    margin-right: auto;
    padding-left: 0.5em;
    padding-right: 0.5em;
}
</style>
</head>
<body>
<hr>
<div class="text">
<span>
My text
</span>
</div>
</body>
</html>

演示:http://jsfiddle.net/EdtwL/

第二个示例,将带有白色背景的文本(将其更改为页面具有的任何背景)放在 HR 上,并将其与 margin-left: automargin-right: auto 居中对齐。

【讨论】:

  • 如何使文本居中?目前它没有居中对齐
【解决方案2】:

您可以创建一个图像,将其设置为像这样重复:

h1 {
background-image: url('line.png');
background-position: center center;
background-repeat: repeat-x;
text-align: center;
}
h1 span {
background-color: #FFF  //Or your website background color if not white

//UPDATE: to add padding around the text:
padding: 5px 10px;
}

然后在 HTML 中:

<h1><span>My text</span></h1>

【讨论】:

  • 如何使用您的示例在文本周围进行填充?所以文字后面没有任何线条?
  • 我已经更新了上面的例子,为 span 标签添加了填充。
【解决方案3】:
<!DOCTYPE html>
<html>
<head><title>Test</title>
<style type="text/css">
div{
    position:relative;
    height:10px;
    border-bottom:1px solid black;
}


span{
    position:absolute;
    left:50%;
    margin-left:-10px;
    background-color:white;
    padding:0px 10px 0px 10px;
}
</style>
</head>
<body>

<div>

<span>My Text</span>

</div>


</body>
</html>

【讨论】:

    【解决方案4】:

    这样的?

    h1:before {
        padding-right: 5px;
        content: "---------------------";
    }
    h1:after {
    padding-left: 5px;
        content: "---------------------";
    }
    

    如果你真的想要一条线而不是破折号,那么我没有解决方案。

    【讨论】:

      【解决方案5】:

      这很简单!

      h2 { text-align: center; /*optional*/ line-height: 2; background: #ccc; }
      h2:before,
      h2:after { padding: 1em; position: relative; top: -.4em; content: '__________________'; }
      

      http://jsfiddle.net/xhj1poj0/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-14
        • 1970-01-01
        • 2019-11-12
        相关资源
        最近更新 更多