[Frontend | CSS-Reihe] – Teil 1: Wie erreicht man eine horizontale und vertikale Mittelausrichtung?

1. Verwenden Sie [Flex-Layout]

.container {
    
    
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

2. Verwenden Sie [Rasterlayout]

.container {
    
    
  display: grid;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

3. Verwenden Sie [Tabellenlayout]

.container {
    
    
  display: table;
}
.child {
    
    
  display: table-cell;
  text-align: center; /* 水平居中 */
  vertical-align: middle; /* 垂直居中 */
}

4. Verwenden Sie [absolute Positionierung] + [Transformationsattribut]

.container {
    
    
  position: relative;
}
.child {
    
    
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

5. Verwenden Sie [absolute Positionierung] + [Randattribut] – (gilt nur für: bekannte Elementbreite und -höhe)

.container {
    
    
  position: relative;
}
.child {
    
    
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px; /* 其中50px是元素宽高的一半 */
}

Einfache Links-Rechts-Mittelausrichtung von Elementen:
Elemente auf Blockebene können verwendet werden magrin: 0 auto;
Elemente auf Nicht-Blockebene können verwendet werdentext-align: center;

Guess you like

Origin blog.csdn.net/sunshineTing2/article/details/132190156