The Method of Realizing the Horizontal and Vertical Centering of Flexible Box in CSS

How to center flexbox horizontally and vertically

In order to achieve responsive layout, use flex elastic box, the layout is as follows

  <div class="app">
    <div id="desktop">
      <h1>你好世界</h1>
    </div>
  </div>

Solution:

.app {
    
    
  width: 100%;	//铺满全屏
  height: 100%;
  display: flex;	//弹性盒子
  justify-content: center;	//水平居中
  align-items: center;	//垂直居中
  background-color: blueviolet;
  border: solid 2px black;
}

#desktop {
    
    
  width: 100px;
  height: 50px;
  background-color: yellowgreen;
  border: solid 2px black;
}

Original effect:
insert image description here
Achieved effect: (the green box is centered horizontally and vertically)
insert image description here

Note: The align-content attribute cannot be used here, because it can only be used when multiple axis alignments are defined. This property has no effect if the item has only one axis.

Supplementary material:
For the justify-content attribute, it may take 5 values, and the specific alignment is related to the direction of the axis. The following assumes that the main axis is from left to right.

flex-start (default): left-aligned
flex-end: right-aligned
center: centered
space-between: aligned at both ends, with equal spacing between items.
space-around: Equal spacing on both sides of each item. So, the spacing between items is twice as large as the spacing between items and the border. As shown below.
insert image description here

The align-items attribute defines how items are aligned on the cross axis, it may take 5 values. The specific alignment is related to the direction of the cross axis, and the following assumes that the cross axis is from top to bottom.

flex-start: The starting point of the cross axis is aligned.
flex-end: The end of the cross axis is aligned.
center: The midpoint of the cross axis is aligned.
baseline: The baseline alignment of the first line of text in the item.
stretch (default): If the item does not have a height set or is set to auto, it will take up the entire height of the container.
insert image description here
Reference material:
Flex Layout Grammar Tutorial
https://www.runoob.com/w3cnote/flex-grammar.html

Guess you like

Origin blog.csdn.net/DCJwwh/article/details/128922135