Vertical And Horizontal Centering Of Elements Using 
 Different Methods.

Vertical And Horizontal Centering Of Elements Using Different Methods.

ยท

2 min read

Introduction

In creating web-page, one issue that is of paramount concern is centering our elements. Here we will take look at four major different css methods in centering our elements. Using:

  1. flex-property
  2. Margin property
  3. Grid property
  4. Position property

Now lets praticalize this, Here is our Html code ๐Ÿ‘‡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div class="parent">
        <div class="child"></div>
    </div>
</body>
</html>
  • Using flex property

    We can use the flex property to vertically and horizontally center our elements by setting the parent div element in our html code to display:flex and then using these two properties to see the full results.
body {
    margin: 0;
    padding: 0;
}

.parent {
    height: 50em;
    display: flex;
    justify-content: center;
    align-items: center;
    border:10px solid black
}
.child {
    height: 24em;
    width: 30em;
    background: blue;
}
  • Using the margin property

    By using display:grid on our parent div, we can horizontal and vertically center our elements with margin: auto property.
body {
    margin: 0;
    padding: 0;
}

.parent {
    height: 50em;
    display: grid;
    border:10px solid black
}
.child {
    height: 24em;
    width: 30em;
    margin: auto;
    background: blue;
}
  • Using the Grid property

    One of the easiest way to center our elements horizontally and vertically is to set our parent elements to the grid and set place-item property to center them.
body {
    margin: 0;
    padding: 0;
}

.parent {
    height: 50em;
    display: grid;
    place-items: center;
    border:10px solid black
}
.child {
    height: 24em;
    width: 30em;
    background: blue;
}
  • Using position property

    Using position property we can horizontally and vertically center our elements
body {
    margin: 0;
    padding: 0;
}

.parent {
    height: 50em;
    position: relative;
    border:10px solid black
}
.child {
    height: 24em;
    width: 30em;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: blue;
}

This is the result after using any of the above method

image.png

Conclusion

Centering elements in our web page is very important ant these are the common ways of vertically and horizontally centering our elements.

ย