Search code examples
cssvertical-alignment

How do I vertically center a pseudo element image in CSS?


There are a couple similar questions I've found out there, but none of the answers have worked. Here's my issue:

I'm trying to insert and center a decorative bracket image before and after some content like this:

Since I have two images, I can't insert them using a background property (in CSS2). So I'm using the :before and :after tags like so:

p#special:before { 
    content: " "url(/images/left-bracket.png);
}
p#special:after { 
    content: " "url(/images/right-bracket.png);
}

Unfortunately, this ends up aligning the images to the baseline of the text like this:

I've tried applying "vertical-align: middle" and "vertical-align: -50%" to the pseudo elements with no success. They move slightly, but not to the middle as demonstrated above.

I've also tried applying vertical-align to the paragraph itself with no success.

I've tried adjusting the height of the paragraph to the height of the image in combination with various vertical-align values.

I've also tried adjusting the line-height of both the paragraph itself, and the pseudo elements. This didn't work either.

I can position the brackets exactly where I want them using something like "position: relative; top: XXpx;" on the pseudo elements, but if I have more than one line of text, or a different font size in some cases, the brackets will no longer be centered. I want the images to always be vertically aligned to the middle of the text. Any ideas?


Solution

  • Try this:

    p#special{
        position: relative;
    }
    p#special:before { 
        content: " "url(/images/left-bracket.png);
        position: absolute;
        top: 50%;
        left: 0px;
    }
    p#special:after { 
        content: " "url(/images/right-bracket.png);
        position: absolute;
        top: 50%;
        right: 0px;
    }