-1

I just can't center the div(Horizontal-Container)both vertically and horizontally and I can't figure out why it's not working...

I've try all the methods by w3school, but either it's not horizontally or vertically center, it can't be both achieved...

Below is my code:

body {
  background-color: #62306D;
}

.Horizontal-Container {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.Yellow {
  background-color: #F7EC7D;
  width: 90px;
  height: 180px;
}
<div class="Horizontal-Container">
  <div class="Yellow"></div>
  <div class="Yellow"></div>
  <div class="Yellow"></div>
</div>
connexo
  • 53,704
  • 14
  • 91
  • 128
Ace
  • 11
  • 5
  • Your items are centered. With `height: auto;` why are you expecting the container to be higher than their content??? You explicitly command the container to be only as high as what is **in it**. – connexo May 15 '21 at 10:26

2 Answers2

-1

Your issue arises from .Horizontal-Container not being full height so it is technically vertically centered, just it hasn't moved. To fix this, you need to set the height of body and html to 100% which then allows the container to have the height you desire. It may seem off centre now, but that is down to padding and margin on the elements which you can easily remove.

html, body {
  background-color: #62306D;
  height: 100%;
  margin: 0; 
  padding: 0;
}

.Horizontal-Container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.Yellow {
  background-color: #F7EC7D;
  width: 90px;
  height: 180px;
}
<div class="Horizontal-Container">
  <div class="Yellow"></div>
  <div class="Yellow"></div>
  <div class="Yellow"></div>
</div>
Hive7
  • 3,599
  • 2
  • 22
  • 38
-1

It's not working because your .Horizontal-Container does not have a specific height. If you set the height to auto it will consume as much space as its children need. Thus you have to add a height either to your container or simply to your body in order to center your elements over the whole page.

body {
  background-color: #62306D;
}

.Horizontal-Container {
  width: 100%;
  height: 100vh; /* <-- set a specific height */
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.Yellow {
  background-color: #F7EC7D;
  width: 90px;
  height: 180px;
}
<div class="Horizontal-Container">
  <div class="Yellow"></div>
  <div class="Yellow"></div>
  <div class="Yellow"></div>
</div>
Behemoth
  • 5,389
  • 4
  • 16
  • 40