Search code examples
cssvertical-alignment

Is it possible to vertically align a :before differently depending on the size of the element?


I have a :before element that I want to vertically align differently depending on the height of the element it's attached to. I'm using it with <blockquote> however I believe my question applies more generally.

I have the following jsfiddle to illustrate: https://jsfiddle.net/06mf93kx/

Basically I'd like the :before element to be aligned to the top of the paragraph (as it is in the fiddle; the second quote is correct there.) However, if the paragraph is only one line, then I'd like the paragraph to be vertically centered with respect to the :before element, something like this:

+-------+
|       |
|       |  Pithy quote.
|       |
+-------+

Is there a way to do this in CSS without resorting to JS to measure the size of the paragraph and adjust the style?

Some things I've tried already: I've tried line-height: 30px on the <blockquote> and this produces the desired result for the one-line case, but of course spaces out the lines in the multiline case. I've tried min-height: 30px on the <blockquote> with top: 50% on the <p>, but this doesn't seem to change anything.


Solution

  • In the end it was Matías' CSS tricks link that pointed me in the right direction.

    Here's what I wanted it to do: https://jsfiddle.net/8utbj2o7/

    Instead of align-items: center, I used align-self:

    blockquote:before {
        align-self: flex-start;
    }
    
    blockquote p {
        align-self: center;
    }
    

    This makes the <p> element center itself only if it's got less height than the :before element.