HomeContact
CSS
How to center elements or <div> with CSS.
April 06, 2020
1 min

To center an element or a div in a <div> or component you can use different approach.

Here is an example of html we have (can work also with all the different javascript framework out there)

<div class="container">
  <div class="child"></div>
</div>

To center the child div in the parent we can use :

.container {
  width: 300px;
  height: 300px;
  background-color: blue;
}

.child {
  margin: auto; /* 0 auto align horizontal/ auto 0 align vertical   */
  width: 100px;
  height: 100px;
}

Note that here we specify only to the children to be centered.

If you want to center by using the css container :

.container {
  width: 300px;
  height: 300px;
  background-color: blue;
  display: flex;
  justify-content: center; /* align horizontal */
  align-items: center; /* align vertical */
}

.child {
  width: 100px;
  height: 100px;
  background-color: red;
}

Tags

css

Related Posts

How to make a div full screen using CSS
June 27, 2022
1 min
© 2023, All Rights Reserved.

Quick Links

Contact Us

Social Media