Horizontal centering images

I am facing a small CSS problem: I have a page with some blocks of content, of which I don’t know the contents on beforehand. Therefore all blocks — defined by div elements — have the same definition. If the block contains text, it has to be left aligned; if the block contains an image, it has to be horizontally centred.

In the good ol’ HTML era, I would simply add align=“center” to the img element, and I would be done. But with CSS, the only way to centre an image is with text-align: center; to the parent element of the image. But this is impossible, since I don’t know the contents on beforehand.

What I would want is to apply a certain style depending on the child element; something like: div < img {text-align:center}. Since this kind of instructions do not exist, I will probably have to use some kind of JavaScript hack to accomplish what I want — or does anybody know a better solution?

Jeroen Sangers @jeroensangers

An IndieWeb Webring 🕸💍