Classless Image Positioning

A while back, I struggled with centering an img between blocks of paragraphs for my blog posts. I eventually found the solution on StackOverflow, but I forgot to bookmark the link and now I lost the source! It was so game-changing that I don't want to go back to making .center class again.

This was the accepted answer:

img[src*="#center"] {
    display: block;
    margin: auto;
}

This is called attribute selector. Quoting from MDN, this selector matches the HTML attribute defined inside the brackets. The code above says to target any img whose src contains "#center".

To make it work, insert an img into your HTML file and add #center in the src like this:

<img src="path/to/your/image.jpg#center" alt="alt text" loading="lazy">

Here's the result!

Tanimura

I really love this approach because it's so, so clean and you don't need to create a class to make it work. If you use an SSG, this also works on Markdown files. It doesn't affect the image link.

You can also place images on the left or right side of a paragraph the same way.

img {
    display: flex;
}

img[src*="#left"] {
  float: left;
}

img[src*="#right"] {
  float: right;
}

Below is how it looks like in image-text-image-text order:

Tanimura

Aenean elementum in velit at interdum. Nulla rutrum non lorem a tempus. Fusce nisl ligula, venenatis at ante eu, sodales iaculis justo. Vivamus vitae neque mollis, fermentum nisl sed, sagittis neque. Donec dapibus odio in turpis fringilla mattis. Praesent turpis lorem, efficitur semper hendrerit quis, finibus vitae sapien. Nulla a rutrum nulla.

Tanimura

Integer fringilla dignissim erat, a fermentum eros vulputate quis. Aliquam nec quam ullamcorper, imperdiet erat in, pretium erat. Duis vel diam et orci fermentum egestas. Nullam aliquam urna eget libero tempor, ut porta turpis fermentum. Suspendisse sit amet pulvinar diam, non facilisis dolor. Morbi tincidunt purus eget lacus mattis mattis. Pellentesque in ex pellentesque, bibendum libero quis, faucibus nisl. Phasellus eu efficitur purus, a fringilla turpis.

I hope it helps somebody out there.