search

Home  >  Q&A  >  body text

CSS Tips: Create Horizontal Lines and Centered Text

<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粉248602298P粉248602298513 days ago528

reply all(2)I'll reply

  • P粉555682718

    P粉5556827182023-08-21 14:12:46

    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/

    reply
    0
  • P粉578680675

    P粉5786806752023-08-21 13:42:39

    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>

    reply
    0
  • Cancelreply