Search code examples
htmlcssbackground-colorpseudo-elementcss-content

background-color on heading with pseudo-element


I am trying to make a heading with a trailing bar. I used the pseudo-element ::after.

My problem is the background color of the heading should "block out" the part of the ::after element that is located "under" the heading itself - but it doesn't.

HTML:

<div>
    <h3>TEST</h3>
    <p>blah blah blah blah blah blah blah blah blah blah blah</p>
    <h3>TEST 2</h3>
    <p>blah blah blah blah blah blah blah blah blah blah blah</p>
</div>

CSS:

body{
    font-size: 0.9em;
    font-family: Arial;
}
div{
    width: 300px;
    margin: 0 auto;
}
h3{
    font-size: 200%;
    background-color: hsl(0, 0%, 100%);
    margin: 0px;
    display: inline-block;
    padding-right: 20px;
}
h3::after{
    content: '';
    display: block;
    width: 300px;
    height: 1.3rem;
    background: hsl(200, 30%, 20%);
    margin-top: -1.7rem;
}

jsFiddle


Solution

  • Position the pseudo-element absolutely...it's also cleaner css.

    JSfiddle Demo

    CSS

    body{
        font-size: 0.9em;
        font-family: Arial;
    }
    
    div{
        width: 300px;
        margin: 0 auto;
    }
    h3{
        font-size: 200%;
        background-color: hsl(0, 0%, 100%);
        margin: 0px;
        position: relative;
        overflow: hidden;
    }
    h3::after{
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        margin-left: 20px;
        background: hsl(200, 30%, 20%);
    

    }