You want to give the headings of your pages an original and attractive style, but you don’t know how? Read this snippet, and you'll learn to add lines before and after the headings. You can get such an effect by using the ::before and ::after pseudo-elements. Let’s do it together step by step.
<h1>Welcome!</h1>
h1 {
font-family: sans-serif;
margin: 100px auto;
color: #228B22;
text-align: center;
font-size: 30px;
max-width: 600px;
position: relative;
}
h1:before {
content: "";
display: block;
width: 120px;
height: 2px;
background: #000;
left: 0;
top: 50%;
position: absolute;
}
h1:after {
content: "";
display: block;
width: 120px;
height: 2px;
background: #000;
right: 0;
top: 50%;
position: absolute;
}
Now let’s put the whole code together and try some examples.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
h1 {
font-family: sans-serif;
margin: 100px auto;
color: #228B22;
text-align: center;
font-size: 30px;
max-width: 600px;
position: relative;
}
h1:before {
content: "";
display: block;
width: 130px;
height: 5px;
background: #191970;
left: 0;
top: 50%;
position: absolute;
}
h1:after {
content: "";
display: block;
width: 130px;
height: 5px;
background: #191970;
right: 0;
top: 50%;
position: absolute;
}
</style>
</head>
<body>
<h1>Welcome to W3Docs!</h1>
</body>
</html>
If you want the lines to be closer to the text, you need to change the left and right positions.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
h1 {
font-family: sans-serif;
margin: 100px auto;
text-align: center;
color: black;
font-size: 40px;
max-width: 600px;
position: relative;
}
h1:before {
content: "";
display: block;
width: 150px;
height: 5px;
background: #CD5C5C;
left: 85px;
top: 50%;
position: absolute;
}
h1:after {
content: "";
display: block;
width: 150px;
height: 5px;
background: #CD5C5C;
right: 85px;
top: 50%;
position: absolute;
}
</style>
</head>
<body>
<h1>Hello!</h1>
</body>
</html>