-1

Can anyone suggest me the fastest way to center a div in CSS ? Thank you !

<div class="wrap">
    <div class="container">
        <p>some content</p>
    </div>
</div>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Samyog Dhital
  • 35
  • 1
  • 9

1 Answers1

0

Example 1: Center div using margin-auto

https://i8pn0.csb.app/margin-auto-example.html

<div class="container">
  <div class="child"></div>
</div>
.container {
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
}

.child {
  width: 50px;
  height: 50px;
  background-color: red;
  /* Center horizontally*/
  margin: 0 auto;
}

Example 2: Center a Div Horizontally using display: flex

https://i8pn0.csb.app/flex-x.html

<div class="container">
  <div class="child"></div>
</div>
.container {
  margin: 25px;
  width: 350px;
  height: 200px;
  /* Center child horizontally*/
  display: flex;
  justify-content: center;
}

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

Example 3: Center a Div Vertically using display: flex

https://i8pn0.csb.app/flex-y.html

<div class="container">
  <div class="child"></div>
</div>
.container {
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
  /* Center vertically */
  display: flex;
  align-items: center;
}

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

These examples are not the only way but the easiest, and some of them only work on modern browsers.

Nawaf Khalifah
  • 594
  • 3
  • 11