CSS 5 ways to vertically center horizontally
- Set Table-cell,text-align,vertical-align for parent element
#big { Width: 200px; height: 200px; border:1px solid #000; display:table-cell; text-align:center; vertical-align:middle;} #small {display:inline-block; width: 50px; height: 50px; background:yellow; vertical-align:middle;}
- Set Margin:auto for child elements
#big {Width200px;Height200px; border:1px solid #000; position:relative; } #small {display:inline-block; width: 50px; height: 50px; background:yellow; position:absolute; left:0; right:0; top:0; bottom:0; margin:auto;}
- Elastic box
#big{ width: 200px; height: 200px; border:1px solid #000; display: flex; align-items: center; justify-content: center; } #small{ display: inline-block; width: 50px; height: 50px; background: yellow; }
- With translate implementation, absolute positioning is performed, and then the translate is used to move itself back 50%
#big {width: 200px; height: 200px; border:1px solid #000; position:relative; } #small {display:inline-block; width: 50px; height: 50px; background:yellow; position:absolute; top: 50%; left: 50%; transform:translate ( -50%,-50%);}
- By creating a new element, set the height of the parent element high, and let the div execute vertical-align with this element
#big {Width200px;Height200px;Border1px solid#000; Text-align:center; }#small {Display:inline-block;Width50px; height: 50px; Background:yellow; Vertical-align:middle; } span{ Display:inline-block; width: 0; height: 100%; background:red; Vertical-align:middle; } </style>< body> <div id= "Big" > <div id= "Small" > </div> <span></span> </div></BODY>
5 ways to align the CSS vertically horizontally