To realize horizontal center/vertical center
I. horizontal center
1.Text-align: center(Line Element)
Set the text-align: center attribute for its parent element;
2.Margin: 0 auto(Block-level elements)
Set margin: 0 auto for the element itself;
3. fixed element width
Margin position + margin-left
. Ele {position: absolute; width: fixed; left: 50%; margin-left:-0.5 width ;}
Margin position + left: 0; right: 0; margin: 0 auto
. Ele {position: absolute; width: fixed; left: 0; right: 0; margin: 0 auto ;}
4. The element width is not fixed
✓ Css3-transform
.ele{ position:absolute; left:50%; transform:translate(-50%,0);}
Trim css3-width: fit-content (you can set the following attributes for the parent element of the element when float: left is set for the element to be centered)
. Ele-parent {width:-moz-fit-content; width:-webkit-fit-content; width: fit-content; margin: 0 auto ;}
This attribute currently only supports Chrome and Firefox browsers.
️ Flex
.ele-parent{ display: flex; justify-content: center;}
2. Vertical center
1. line-height: eleparent-height
You can set properties for vertical center of a single line of text.Line-height: parent element height
2. fixed element height
Position + margin-top
. Ele-parent {position: relative;}. ele {position: absolute; top: 50%; height: fixed; margin-top:-0.5 ;}
BytesPosition + top: 0; bottom: 0; margin: auto 0
. Ele {position: absolute; height: fixed; top: 0; bottom: 0; margin: auto 0 ;}
3. The element height is not fixed
Invalid vertical-align
.ele-parent{ display:table;}.ele{ display:table-cell;
vertical-align:middle;}
✓ Css3-transform
.ele{ position:absolute; top:50%; transform: translate(0,-50%);}
BytesFlex
.ele-parent{ display: flex; align-items:center;}
Only these shortcomings can be found. Please criticize and correct them !!!