简体   繁体   中英

How to make a line before and after my h1 tag?

I've search around for a bit to find a solution on how I can make something like this:

----------- My text -------------- In HTML/CSS. So I need a hr tag before and after my text.

Anyone know how this can be fixed?

<!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>

Demo: http://jsfiddle.net/cKrqK/

However, if you are not happy that the HR's don't extend all the way to the edges of the page due to 40% width, this is how you can solve it.

<!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>

Demo: http://jsfiddle.net/EdtwL/

The second example, places your text with a white background (change it to whatever background your page has) on the HR and center-aligns it with margin-left: auto and margin-right: auto .

You could create an image, set it to repeat like so:

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;
}

Then in HTML:

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

This is very simple!

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/

<!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>

Something like this?

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

If you really want a line and not dashes, then I don't have a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM