How to Horizontally & Vertically Center an Absolutely Positioned Div Using Tailwind CSS?

By Hemanta Sundaray on 2022-09-08

Let's say we have an absolutely positioned div, as shown below:

import React from "react"

const Box = () => {
  return (
    <div className="absolute top-0 right-0 w-60 h-12 bg-gray-200 border-2 border-gray-400"></div>
  )
}

export default Box

Absolute Position

Center Horizontally

To horizontally center the div, apply the classes: absolute left-0 right-0 m-auto.

import React from "react"

const Box = () => {
  return (
    <div className="absolute left-0 right-0 m-auto w-60 h-12 bg-gray-200 border-2 border-gray-400"></div>
  )
}

export default Box

Centered Horizontally

Center Vertically

To vertically center the div, apply the classes: absolute top-0 bottom-0 m-auto.

import React from "react"

const Box = () => {
  return (
    <div className="absolute top-0 bottom-0 m-auto w-60 h-12 bg-gray-200 border-2 border-gray-400"></div>
  )
}

export default Box

Centered Vertically

Center Both Horizontally & Vertically

To center the div both horizontally & vertically, apply the classes: absolute top-0 right-0 bottom-o left-0 m-auto.

import React from "react"

const Box = () => {
  return (
    <div className="absolute top-0 right-0 bottom-0 left-0 m-auto w-60 h-12 bg-gray-200 border-2 border-gray-400"></div>
  )
}

export default Box

Centered Horizontally & Vertically

Join the Newsletter