Center your HTML elements Horizontally

 

How to center your element horizontally?

Center your link, text, image and div block horizontally with CSS property. 

You can apply these properties for different situations and what your circumstances are. 

1. text-align property:

You can use this property to center the text and link horizontally on all viewport size. 

Example


.text-center {
     text-align : center;
    }

This will work for all inline element. 

Even you can center all your child element if you set this property to your parent element. 

Center your inline element horizontally


2. Margin auto:

If you are centering a block level element horizontally, you can do it with margin in simple way. 

Note: Make sure to give your block element a width property or else it will take whole space and your margin won't take any effect. 


.card {
    width : 300px;
    margin : 0 auto;
  } 

You can also use margin-auto to make inline element center horizontally including - image, button with display:block or display:flex.

Example -


.button {
    display : block;
    margin : 0 auto;
  } 

.img {
    display : block;
    margin : 0 auto;
  } 

Center horizontally a block level element with margin


3. Flexbox:

Use flexbox features on the parent element with justify-content to align your item center horizontally. 


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

Center in css with flexbox


4. Absolute:

You can place your block level element in horizontally center using position.

-Using left, right and auto margin


.parent {
    position : relative;
  } 
.item {
    position : absolute;
    left : 0;
    right : 0;
    margin : 0 auto;
  } 

-Using transform for responsive behavior


.parent {
    position : relative;
   } 
   
.item {
    position : absolute;
    left : 50%;
    -webkit-transform : translateX(-50%);
    transform: translateX(-50%);
    }

left : 50% is relative to the parent element and uses translateX() to move an element horizontally.

Center horizontally with position absolute

Note: add position: relative to the parent element or else both example will not work.

If you have any questions regarding this don't hesitate to ask me.

0 Comments:

Post a Comment