Can't center absolute position (Tailwind.css)

John Cliven picture John Cliven · Feb 23, 2020 · Viewed 7.5k times · Source

Background & Problem:

I'm using Tailwind CSS and Alpine.js for a simple search bar that has a dropdown positioned using absolute

Codepen here: https://codepen.io/jdonline/pen/YzXpbyJ

When I position the dropdown using relative, it positions perfectly as I want it to (but stretches the rest of the page which I don't want). However, when I change this to absolute, although it no longer stretches the page, it extends the dropdown wider than expected.

Example:

You can see this by clicking the dropdown arrow on the right side of the search bar. You can also see the difference when changing absolute to relative on Line 26

Question:

How can I, using Tailwind.css, position the dropdown so it has absolute position, but doesn't extend wider than the search bar?

Answer

Davide Casiraghi picture Davide Casiraghi · Feb 4, 2021

I found my answer in this proposal on the Tailwind Github profile. https://github.com/tailwindlabs/tailwindcss/discussions/1531

Adding this utility class it works perfectly:

.inset-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}