Search code examples
htmlcsshtml-heading

Long title (multiple lines) in heading with line-height


I'm creating a H1 title with css, and added a line-height to it, so the H1 element has the right height and the text is vertically centered.

The problem is with long titles which need multiple lines.

An example is created at jsfiddle: https://jsfiddle.net/wygpfbm3/

HTML:

<h1>
This is a normal title
</h1>


<h1>
This is a very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long title
</h1>

CSS:

h1 { background-color: #ebebeb; border: 1px solid #c7c7c7; border-left: none; border-right: none; top: 0px; line-height: 44px; font-size: 18px; font-weight: normal; color: #3e3e3e; }
h1:before { content: ''; background-color: transparent; border: 6px solid #c7c7c7; border-color: #c7c7c7 transparent transparent #c7c7c7; float: left; }
h1:after { content: ''; border: 6px solid #fff; border-color: #fff transparent transparent #fff; float: left; margin-left: -12px; margin-top: -1px; }

As you can see in the fiddle example, a normal title (single line) is working perfect. When it's a long title, the lines are too far apart (because I set the line-height).

Also the second line doesn't have the padding on the left like the first line. Another problem is with the little white triangle in the top left corner. It's moved down when the title is multiple lines long.

Anyone know how I can solve this in a clean way, preferred with CSS only?


Solution

  • You set the line-height to 44px, presumably so that it will be 44px as a single line.

    So, instead of using line-height why not use top & bottom padding instead

    44px - 18px (font-size) / 2 = 13px padding

    h1 {
      background-color: #ebebeb;
      border: 1px solid #c7c7c7;
      border-left: none;
      border-right: none;
      padding: 13px 0px;
      font-size: 18px;
      font-weight: normal;
      color: #3e3e3e;
      width: 80%;
      margin: 3em;
      position: relative;
    }
    h1::after {
      content: '';
      position: absolute;
      top: -1px;
      left: 0;
      border-width: 6px;
      border-style: solid;
      border-color: white transparent transparent white;
    }
    h1::before {
      content: '';
      position: absolute;
      border-width: 6px;
      border-style: solid;
      border-color: #c7c7c7 transparent transparent #c7c7c7;
      top: 0;
      left: 1px;
    }
    <h1>
    This is a normal title
    </h1>
    
    
    <h1>
    This is a very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long title
    </h1>