Creating a BFC can solve the problems of height collapse, centering, and overlap of margins.
1. Floating element float is not none
2. Absolute positioning or fixed positioning: position: absolute/fixed
3. Inline elements: display: inline-block;
4. overflow Block-level elements that are not visible
5, display value is flow-root, table single element table-cell, table caption table-caption
6, anonymous table cell element
1. The level is centered
Block-level element
Method 1: auto
Note: This element cannot be floated, absolutely positioned, or fixedly positioned
margin: 0 auto;
Method 2: calc Note: There must be a space between the two values
position: relative / absolute / fixed;
left: calc(50% - 元素宽的一半px); 四则运算
top: calc(50% - 元素高的一半px); 垂直居中
Method 3: Flexible Box
父级元素属性
display: flex; 弹性盒子
flex-direction: row; 主轴方向为水平方向,起点在左端
justify-content:center;
Method 4: Positioning
position: absolute;
left: 50%;
margin-left: -元素的一半宽px; / transform: translate(-50%,0);
2D变换中的属性,延x轴移动自身的-50%
Elements in the line
text-align: center; /* 父元素 */
Note: Calc low version IE does not support
2. Vertically centered
Inline element : parent element attribute, and the parent element must be a block element
Method one (multi-line text is invalid): this only means vertical centering in a certain line
line-height:父元素的高; 将字体高度调整为div的高度
vertical-align: bottom; 暂未理解,底部对齐
Method two ( IE8
not supported):
relative positioning of the parent element relative
, which must have a fixed height, and absolute positioning of the child elementabsolute
子元素属性
top: 50%;
transform: translate(0,-50%); / calc(50% - 一半高度) /margin-top: -(一半高度);
Method 3: Flexible box (compatibility issues, IE does not support, mobile browsers support)
Principle: The content on the cross axis is centered on the axis
父类属性
display: flex;
align-items:center;(垂直居中)
Block-level elements
Method 1: Flexible box
display: flex;
display: -webkit-flex;
justify-content: space-between;
align-items: center;
Method 2: Flexible Box
父元素:display:flex;
子元素:align-self:center;
Method 3: vertical-align, IE is not compatible
父元素{
display: table-cell / inline-block;
vertical-align: middle;
}
Method 4: Absolute positioning
父元素relative
子元素{
position: absolute;
top: 50%;
margin-top: -自身高度的一半;
}
Method five: pseudo-element before
父元素::before{
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
子元素 {
display: inline-block;
vertical-align: middle;
}
Method six: transformY
子元素{
position: relative;
top: 50%;
transform: translateY(-50%);
}
3. High collapse
Method 1: Make the parent element float float
Method 2: Clear the float clear: both;
Method 3: Fix the width and height of the
parent element Method 4: Add overflow: hidden;
Method 5: Universal removal method: after pseudo element + clear Floating html part
父元素::after {
content: '';
height: 0;
clear: both;
display: block;
}