Partial Borders with CSS

On July 28, 2014, in Web Development, by Anuj Gakhar

There is no such thing as border-length in CSS, which would have made this really easy to do. But anyway, if you want to have partial borders (a border that spans only half the length of the div e.g.), you can use the before/after pseudo selectors for this. You shouldn’t have to change any markup at all and this is a CSS only solution.

[js]
<html>
<head>

<style>
.mainDiv {
width: 200px;
height: 50px;
border: 5px solid red;
position: relative;
}

.mainDiv:after {
content: ”;
display: block;
position: absolute;
width: 100px;
top: -5px;
left: 0px;
border: 5px solid white;
}
</style>

</head>
<body>

<div class="mainDiv"></div>

</body>
</html>
[/js]

You can also this do this as a LESS mixin if you like, although this may need some more work to accomodate left and right borders.

[js]
.partial-border (@border-width, @partial-width, @color) {
content: ”;
display: block;
position: absolute;
width: @partial-width;
top: -@border-width;
left: 0px;
background: @color;
border: @border-width solid @color;
}
[/js]

Here is a working jsFiddle.

[Update 30/01/2016]
Webucator recently offered to make a video of this blog post and post it on Youtube. So, I am posting it here as well for readers.

Tagged with:  

2 Responses to Partial Borders with CSS

  1. Good post – I’ve used something similar to place over box shadow, so that the shadow only occupies a certain portion of the content div.

  2. Good post, I’ve used it (or more to the point, will use it) in my next project where the Call to Action has only a partial box drawn around it. First I was all “grrr” at the designer 😛

    Seems to work well in a fiddle if I use :before for the top line (80% of the div width), normal border-left, and :after for the bottom line (50% of div width)

Leave a Reply to Sean Vandenberg Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: