HomeCSS3 Ways To Center Stuff With CSS

3 Ways To Center Stuff With CSS

Centering things in CSS can be frustrating. There are a number of methods you can use for centering. But they can get confusing as different scenarios need different approaches. Today we look into 3 Methods we can use to center divs, text, and images. We only explore methods to center things both horizontally and vertically.

Method 1: Using Transforms:

This method is the best to use when the dimension of the container as well as the element is unknown. You can use this method to center both inline and block elements. First of all, we position the element 50% from the top and left of the container. To further adjust the positioning we translate to the top right by 50% of its own height and width.

.demo{
   position: absolute;
   transform: translate(-50%,-50%);
   top: 50%;
   left: 50%;
}
Method 2: Margin Auto:

This method is the best to use when the dimension of the container is unknown but the dimension of the element is known. It fails to work when the dimensions of the element are not defined. Now that the dimensions are defined, the browser can split the remaining space between the margins. This method is perfect for centering block elements of fixed height and width.

.demo{
   position: absolute;
   margin: auto;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
}
Method 3: Flexbox:

This is my favorite method. This method does not need the dimensions of the element to be specified. It can be used to space and center multiple elements. The following CSS styles are applied to the container of the element to be centered. The dimensions of the container need to be specified for this approach to work. Align-items property controls the vertical alignment whereas Justify-content controls the horizontal alignment.
In case, you need to center the element with respect to the screen, just add these styles to the document body. You can use this method to center any inline or block element quickly. You can watch the video tutorial here.

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

That’s it for this tutorial. If you like the tutorial do drop a comment below. To stay updated with the latest tutorials subscribe to us on Youtube or Follow Us on Instagram. You can download the source code below.

RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

nineteen − nineteen =

Most Popular