Skip to main content

Command Palette

Search for a command to run...

4 Quickest way to center element in CSS

Published
2 min read
4 Quickest way to center element in CSS
R

19, Hustler.

Centering element in CSS is hard and confusing for the learning developers. My latest post regarding centering element in CSS by 4 quick ways. We gonna use some CSS property to center them.


HTML

Let's take an example of HTML that we will center.

<div class="parent">
    <p class="child">
        I'm Awesome
    </p>
</div>

Let's Center using CSS

1. Flex Property
-> The flex property sets the flexible length on flexible items.

.parent{
       display: flex;
       justify-content: center;
       align-items: center;
  }

Note: If the element is not a flexible item, the flex property has no effect.


2. Position Property

The position property specifies the type of positioning method used for an element.

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

3. Grid Property The grid CSS property is a shorthand property that sets all of the explicit and implicit grid properties in a single declaration.

 .parent {
     height: 100vh;
     display: grid;
     palce-items: center;
 }

4. Margin Property
The margin property sets the margins for an element.

.parent {
   height: 100vh;
   display: grid;
 }
.parent .child{
  margin: auto;
  }


Thanks For Reading ♥
Let me know about this post in the comments.
Originally here -> https://rahulism.co/center-using-css

*

It's always good to have the basics around. Thank you!

2
R
Rahul5y ago

Ah! Yes. Hope You Liked This Post.

C

Hey Rahul, for option one you need the 100vh as well, else the vertical height will be only how tall your children are.

1
R
Rahul5y ago

Ah yes. Thanks.

E

Awesome article Rahul. Thanks for sharing.

3
R
Rahul5y ago

Thank You.

More from this blog

R

RAHULISM - FrontEnd Web Developer

232 posts

18, Hustler.