CodingSparkles

Two Simple Ways to Centering an Element (Div)

CSS
1 min read
October 04, 2021
Two Simple Ways to Centering an Element (Div)

In this article, I’m going to share two easy ways to center the element using CSS. Let’s go through the ways to center a Div element using CSS.

HTML Element

<div class='parent'>
  <div class='child'>Coding Sparkles</div>
</div>

Basic Style

.parent {
  height: 10em;
  border: 2px solid blue;
}

.child {
  background: blue;
  color: white;
  height: auto;
  width: 5em;
  text-align: center;
}

To center the Div element vertically and horizontal,

Using Flex

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
  • Apply the above styles to a parent element

  • Check out the working code example in the following codepen

Using Grid

.parent {
  display:grid;
}

.child {
  justify-self: center;
  align-self: center;
}
  • Apply the above styles to the parent and child

  • Check out the working code example in the following codepen

There are other ways to achieve this scenario, but I feel that both of the above methods are simple. What you are feeling, share your thoughts.

Share:
This website uses cookies to ensure you get the best experience on our website.More Information