0

I'm just wondering why margin auto isn't working? my parent div margin auto works but my inner margin auto is not in center.

.rankings_page{
    width: 750px;
    background-color: #f5f5f5;
    margin: auto;
    height: 800px;
}
.tab-group {
    margin: auto;
}
.toggle_btn{

    background-color: blue;
    float: left;
    width: 30%;
    text-align: center;
    cursor:pointer;
}
<div className="rankings_page">
    <div className="tabgroup">
        <div className="toggle_btn">
            Country
        </div>
        <div className="toggle_btn">
            City
        </div>
      </div>
    </div>
</div>

Thanks!

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    By "not centering" I suppose you mean "not centering vertically"? You can't use `margin: auto` to center an element vertically: use flexbox instead. – Terry Mar 15 '20 at 21:42
  • div will have full width by default so there is nothing to center – Temani Afif Mar 15 '20 at 21:46

1 Answers1

1

The margin: auto trick only works if you want to horizontally center your elements. It will not work to vertically center your elements, because of how CSS deals with vertical margins differently.

You should use CSS flexbox instead: it is specifically made to allow layouts like this possible:

display: flex;
align-items: center;
justify-content: center;

Also, you need to update the tabgroup selector, because there is no - in the class in your markup. See proof-of-concept example:

.rankings_page {
  width: 750px;
  background-color: #f5f5f5;
  height: 800px;
  
  display: flex;
  align-items: center;
  justify-content: center;
}

.tabgroup {
  display: flex;
}

.toggle_btn {
  background-color: blue;
  cursor: pointer;
}
<div class="rankings_page">
  <div class="tabgroup">
    <div class="toggle_btn">
      Country
    </div>
    <div class="toggle_btn">
      City
    </div>
  </div>
</div>
Terry
  • 63,248
  • 15
  • 96
  • 118