CSS Only Partial Width Borders

A design that I was recently implementing required a partial width underline for some headings and a partial height border as a divider between two elements.

But I didn’t want to add any extra elements to the DOM to get there. Because, well... why would I want to add non-semantic elements if it can be avoided?

The solution I came up with is pretty simple really. It uses a :before to handle positioning and sizing the border.


  .partial-border: {
    display: inline-block;
    position: relative;
  }
  .partial-border:before {
    content: ’’;
    position: absolute;
    bottom: 0;
    width: 80%;
    left: 10%; /*this centers it based on the above width*/
    border-bottom: 1px solid lightcoral;
  }

That pretty much does the trick... no extra markup and partial width borders.

The position: relative on the parent is to allow its width to dictate the width of the absolutely positioned pseudo element. Other then that it’s pretty self-explanatory.

If you want to play around with this yourself it is on codepen. Enjoy!

Published: 8 Jul 2016 | Tags: css , dev , development , code