James Allardice
James Allardice

Reputation: 165941

Is it possible to vertically center generated content?

Suppose I have a div with the following styles applied:

div {
    border: 1px solid #000;
    padding-left: 35px;
    position: relative;
}

To that div I apply a :before pseudo-element. The content of that pseudo-element is an image:

div:before {
    content: url(someImage.png);
    background-color: #ccc;
    position: absolute;
    left: 0;
    width: 30px;
    height: 100%;
}

The height of the div is dynamic. Is there any way I can vertically center the image that is part of the generated content?

Here's a fiddle with an example.

I can't use line-height since I don't know the height of the div. I can't use a margin or padding since the generated content has a background colour that would expand beyond the div. I suspect the answer is "no", but thought it might be worth asking here before I have to go and change a lot of markup!

Upvotes: 1

Views: 180

Answers (1)

BoltClock
BoltClock

Reputation: 723428

It should theoretically be possible as it's nothing more than a CSS version of a regular inline <img> tag, but that depends largely on its formatting (and possibly that of the generating element).

For simplicity, I would make it a background image instead, with an empty string for its content:

div:before {
    content: '';
    background: #ccc url(someImage.png) center center no-repeat;
    position: absolute;
    left: 0;
    width: 30px;
    height: 100%;
}

Notice that I'm taking advantage of the fact that you already have the gray background adequately covering the generated area — I simply center the image over that gray background.

Updated fiddle

Upvotes: 8

Related Questions