CSS – Border where only half of a border is visible

If you do not want to mess with the HTML at all, you can do it with an empty pseudoelement, using CSS only. You still need to know the background color, of course (assuming white here):

<span class="half-a-border-on-top">Hello world!</span>

<style>
.half-a-border-on-top {
  border-top:1px solid black;
  position: relative;
}
.half-a-border-on-top:after {
  padding:0;margin:0;display:block;/* probably not really needed? */
  content: "";
  width:50%;
  height:1.1px;/* slight higher to work around rounding errors(?) on some zoom levels in some browsers. */
  background-color:white;
  position: absolute;
  right:0;
  top:-1px;
}
</style>

Result:

Half of a top border visible above the text "Hello world"

Snippet

    .half-a-border-on-top {
      border-top:1px solid black;
      position: relative;
    }
    .half-a-border-on-top:after {
      padding:0;margin:0;display:block;/* probably not really needed? */
      content: "";
      width:50%;
      height:1.1px;
      background-color:white;
      position: absolute;
      right:0;
      top:-1px;
    }
    <span class="half-a-border-on-top">Hello world!</span>

Fiddle:

http://jsfiddle.net/vL1qojj8/

Edit 2023: Now that even Safari seems to fully and properly support linear-gradient, the answer by 红了樱桃绿了吧唧 is probably more elegant, and will work without knowing the background color.

Leave a Comment