0

I have a container div which has other divs and contents within it and I am trying to center the outer div.

For example:

body {
  height: 100vh;
  width: 100vw;
}

.test {
  width: 20vw;
  height: 20vh;
  background-color: green;
}

.outer-test {
  display: block;
  margin: auto;
}
<div class="outer-test">
  <p>Hello</p>
  <div class="test"></div>
</div>

In the example above, how would I be able to center the div with class of "outer-test"? I have tried to make the display: block and use margin: auto but that doesn't seem to be working.

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
chibiw3n
  • 357
  • 2
  • 15

1 Answers1

1

Option 1: You can use display: flex on the body

body{
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center; // Centers in the direction of flex-direction (default is row)
  align-items: center; // Centers in the direction normal to flex-direction
}
.test{
  width: 20vw;
  height: 20vh;
  background-color: green;
}
<body>
  <div class="outer-test">
    <p>Hello</p>
    <div class="test"></div>
  </div>
</body>

Option 2: You can use a wrapper around your outer div.

body {
  height: 100vh;
  width: 100vw;
}
.test {
  width: 20vw;
  height: 20vh;
  background-color: green;
}
.center {
  display: flex;
  justify-content: center;
}
<body>
<div class="center">
  <div class="outer-test">
    <p>Hello</p>
    <div class="test"></div>
  </div>
</div>
</body>
Timothy Alexis Vass
  • 2,526
  • 2
  • 11
  • 30