How to center div in tailwind?


I was looking at this question: How to center div horizontally and vertically using flexbox? this works good when using custom CSS, but how can I align div to center using Tailwind CSS class, veritically and horizontally. Since, I am already using Tailwind in a project, so I suppose I can use it instead of custom CSS.


Asked by:- neena
1
: 1073 At:- 10/5/2022 4:08:42 PM
CSS tailwind center div







2 Answers
profileImage Answered by:- vikas_jk

You can use tailwind CSS class, '.flex', '.h-screen' for main div and '.m-auto' for inner div, as shown below:

<link rel="stylesheet" href='https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css' />

<div class="flex h-screen">
  <div class="m-auto">
    <h3>title</h3>
    <button>button</button>
  </div>
</div>

<div id="mainContainer" class="flex h-screen">
    <div  class="m-auto">
        <p>Some Text</p>
    </div>
</div>

Here is the working fiddle link https://jsfiddle.net/wq0ap5vr/

'h-screen': Sets the 100vh (screen-height) as the height

'.flex': just adds "display:flex" to outer div

and '.m-auto': gives margin: auto to inner div

Using Flex-center Class

<div class="flex items-center justify-center h-screen">
  Centered div using Tailwind Flex
</div>

Hope this helps.

2
At:- 10/5/2022 4:16:08 PM
Thanks for excellent and quick answer, it helped. 0
By : neena - at :- 10/5/2022 4:18:58 PM


profileImage Answered by:- Vinnu

You can also do it with grid

<link rel="stylesheet" href='https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css' />

<div class="grid justify-items-center items-center h-screen">
  <div>
    <h3>Hello</h3>
    <button>This is just a button</button>
  </div>
</div>

Fiddle: https://jsfiddle.net/5qezpwmj/

Hope it helps.

0
At:- 10/14/2022 3:38:34 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use