CSS Tips: Create Horizontal Lines and Centered Text
P粉248602298
P粉248602298 2023-08-20 15:11:18
0
2
517
<p>I'm trying to make a horizontal divider with some text. For example: </p> <p>---------------------------------- Here is my title------ -----------------------</p> <p>Is there a way to achieve this effect in CSS? Obviously there is no need to use all the "-" dashes. </p>
P粉248602298
P粉248602298

reply all(2)
P粉555682718

After trying different solutions, I found a solution that works for different text widths, any possible background and without adding extra markup.

h1 {
  overflow: hidden;
  text-align: center;
}

h1:before,
h1:after {
  background-color: #000;
  content: "";
  display: inline-block;
  height: 1px;
  position: relative;
  vertical-align: middle;
  width: 50%;
}

h1:before {
  right: 0.5em;
  margin-left: -50%;
}

h1:after {
  left: 0.5em;
  margin-right: -50%;
}
<h1>标题</h1>
<h1>这是一个较长的标题</h1>

I tested in IE8, IE9, Firefox and Chrome. You can check it here: http://jsfiddle.net/Puigcerber/vLwDf/1/

P粉578680675

This is roughly how I would do it: by setting border-bottom on the containing h2, and then giving h2 a smaller line-height to create lines. Then put the text inside a nested span with a non-transparent background.

h2 {
   width: 100%; 
   text-align: center; 
   border-bottom: 1px solid #000; 
   line-height: 0.1em;
   margin: 10px 0 20px; 
} 

h2 span { 
    background:#fff; 
    padding:0 10px; 
}
<h2><span>这是一个测试</span></h2>
<p>这是一些其他内容</p>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template