swjh
All posts

How to preserve Aspect Ratio of Images with Tailwind CSS

   ⬪   Updated:    ⬪   1 min read
#css#tailwindcss

With these few tailwind classes you can lock the aspect ratio of an image. In this example the height will be 2/3rds of the height.

<div class="relative overflow-hidden pb-2/3">
  <img src="" alt="" class="absolute h-full w-full object-cover" />
</div>

Since percentage values for spacing are not available per default you’ll need to add it in tailwind.config.js like so:

module.exports = {
  theme: {
    extend: {
      spacing: {
        "2/3": "66.666667%",
      },
    },
  },
};

More details in the Tailwind Docs