Vertical Center Layout Please move: Vertical center layout

Width is known

Structure:

<div id="parent">
  <div id="child"></div>
</div>
Copy the code

Style:

#parent {
  width: 400px;
  height: 300px;
  background-color: lightskyblue;
}

#child {
  width: 80px;
  height: 60px;
  background-color: lightpink;
}
Copy the code

1. Position: Absolute + margin-left

  • Traditional scheme
  • Recommended index: ☆☆☆☆
#parent {
  position: relative;
}

#child {
  position: absolute;
  left: 50%;
  margin-left: -40px;
}
Copy the code

2, Position: Absolute + calc()

  • Can I use ?
  • Recommended index: * * * * (Poor compatibility)
#parent {
  position: relative;
}

#child {
  position: absolute;
  left: calc(50% - 40px);
}
Copy the code

Margin: 0 auto

  • Block-level elements
  • ☆☆☆ (Applicable scenarios have limitations)
#child {
  margin: 0 auto;
}
Copy the code

Width unknown

Structure:

<div id="parent">
  <div id="child">hello world</div>
</div>
Copy the code

Style:

#parent {
  width: 400px;
  height: 300px;
  background-color: lightskyblue;
}

#child {
  height: 60px;
  background-color: lightpink;
}
Copy the code

Display: flex + justify-content: center

  • Mainstream mobile solutions
  • Can I use ?
  • Recommended index: ☆☆☆☆
#parent {
  display: flex;
  justify-content: center;
}
Copy the code

2, display: grid + context-content: center

  • Can I use ?
  • ☆☆ (They are overqualified for work; Poor compatibility)
#parent {
  display: grid;
  justify-content: center;
}
Copy the code

Position: Absolute + transform: translateX()

  • Can I use ?
  • Recommended index: * * * * (Poor compatibility)
#parent {
  position: relative;
}

#child {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
Copy the code

4, display: table + margin: 0 auto

  • Similar to the<table align="center">
  • Can I use ?
  • Recommended index: ☆☆☆ (Evil way)
#child {
  display: table;
  margin: 0 auto;
}
Copy the code

5, text-align: center + display: inline-block

  • Can I use ?
  • * * * * (Slightly less compatible)
#parent {
  text-align: center;
}

#child {
  display: inline-block;
}
Copy the code