How To Make An Elegant Two Color Top Border With CSS

I’ve been working on what seems to be a very simple task: make an elegant two-color border similar to the one pictured above. As the page expands, it should expand to black on the right and purple on the left while staying centered.

It seems like I’ve tried everything from using the border-top CSS property to setting a background-image in the body, but nothing worked. I finally found this great articleย on CSS Tricks that finally helped me figure it out. The key was absolute positioning, setting the width to 50%, and setting the left or right to 0px.

My code is below, but make sure to look at the DEMO (don’t forget to resize the DEMO window for the cool part!).

HTML

<!DOCTYPE html>
<html lang='en' xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Two Color Border</title>
    </head>
    <body>
        <div id="border">
            <div id="purple"></div>
            <div id="black"></div>
        </div>
    </body>
</html>โ€‹

CSS

#border {
    margin-top: 0px;
}

#purple {
    background-color: #802961;
    display: inline-table;
    height: 10px;
    width: 51%;
    left: 0px;
    background-repeat: repeat-x;
    position: absolute;
}

#black {
    background-color: #1A0512;
    display: inline-table;
    width: 50%;
    right: 0px;
    height: 10px;
    background-repeat: repeat-x;
    position: absolute;
}

Do you know of a better way of making this? If so, please let me know in the comments!

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • Awesome job!! This is a clever way of doing it. I’m wondering if there are any other ways that don’t require the additional HTML

  • Hey Natasha,

    I am a big fan of your site!

    I am no expert but here’s my take on the challenge above:
    http://jsfiddle.net/ajmalafif/mczZZ/1/

    • Ooh, nice solution with the float right and left! I’m still hoping someone would figure out how to do this in the body tag with the border property, so not purple and black divs are needed in the HTML.

  • Jauny

    Natasha, is there any reason why purple is 51% and not 50%?

    • Try it out with 50%! Without the 51%, the purple and the black don’t connect in the middle.

      • Jauny

        I see, cool ๐Ÿ™‚