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.

<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>

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.

.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;
}

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

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 445 other subscribers

© 2011 Anuj Gakhar
%d bloggers like this: