DEV Community

Cover image for 4 Quickest way to center element in CSS
Rahul
Rahul

Posted on • Originally published at rahulism.co

4 Quickest way to center element in CSS

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>
Enter fullscreen mode Exit fullscreen mode

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;
  }
Enter fullscreen mode Exit fullscreen mode

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%);
 }
Enter fullscreen mode Exit fullscreen mode

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;
 } 
Enter fullscreen mode Exit fullscreen mode

4. Margin Property

The margin property sets the margins for an element.

.parent {
   height: 100vh;
   display: grid;
 }
.parent .child{
  margin: auto;
  }
Enter fullscreen mode Exit fullscreen mode



Thanks For Reading ♥

Let me know about this post in the comments.

Originally here -> RAHULISM

Top comments (3)

Collapse
 
ravigithub profile image
Ravi Kasireddy

Awesome.

Collapse
 
pipic1 profile image
Pierre Pic

awsome!!

Collapse
 
rahxuls profile image
Rahul

Thanks