The following editor will bring you a brief analysis of 5 ideas for achieving horizontal and vertical centering with CSS. The editor thinks it’s pretty good. Now I’ll share it with you and give it a reference. Let’s follow the editor and take a look.
Horizontal centering and vertical centering have been introduced separately. This article will introduce horizontal and vertical centering at the same time. 5 ideas
Idea 1:text-align+line-heightachieve horizontal and vertical centering of a single line of text
XML/HTML CodeCopy content to clipboard
<pclass="test"style="background-color: lightblue;width: 200px;">Test text p>
# Idea 2:text-align +vertical-align
【1】Set text-align and vertical-align on the parent element, set the parent element to the table-cell element, and set the child element to the inline-block element [Note] If it is compatible with IE7-browser, change the structure todisplay:inline;zoom:1; to achieve inline- The effect of block
测试文字
##Three ideas:margin+ vertical-align If you want to set vertical-align in the parent element, it must be set to the table-cell element; if you want margin:0 auto to achieve horizontally centered block element content to expand the width, it must be set to table element. The table element can be nested inside the tabel-cell element, just like a cell can nest a table
[Note] If it is compatible with IE7-browser, the structure needs to be changed to
Use absolute【1】Use thebox model
based on the offset being a certain value.
测试文字
【2】Use the offset attribute of the absolutely positioned element and the own offset of the translate()
function
[Note]IE9-browser does not support
测试文字
【3】When the width and height of the child element are known Below, you can use the negative value of margin to achieve the horizontal and vertical centering effect
测试文字
##Idea 5:
Use flex [Note] IE9-browser does not support[1] Use margin:auto
The above is the detailed content of Detailed explanation of 5 ideas for achieving simultaneous horizontal and vertical centering with CSS. For more information, please follow other related articles on the PHP Chinese website!