Element Center, is the front-end workers a commonplace topic, online related information A lot, different people have different understanding (do not exclude direct copy), here I from the actual project needs, after many tests and summary, the following several center method for everyone to try and correct:
1. Simply Center horizontally:
(1) When the element width is known, the assumption is 200px, you can use the positioning + negative margin, the code is as follows:
. Container {position:relative} . Box {position:absolute; Left:50%; margin-left:-100px;}
(2) The element width is unknown or cannot be read directly, the text can be centered, the code is as follows:
. Container {text-align:Center} . Box {display:inline-block}
(3) If you are centering a floating element horizontally, you need to set a div in the outer layer of the element and in the middle of the container, with the following code:
. Box-wrap {float:left; position:relative; Left:50%}. box{float:left; Position:relative; Left:-50%}
Note: The above. Box-wrap is not the outer parent element of the beginning, but a layer of nested elements that are regenerated, plus the left:-50% of box can be replaced with right:50%
2. Simply vertical centering:
(1) When the height of the element is known, it is similar to the width of the above element, and is also a position + negative margin (just replace left with top).
(2) The element height is unknown or cannot be read directly, the text can be centered, the code is as follows:
. Container {height:500px; line-height:500px}. box{display:inline-box; Vertical-align:Middle}
(3) The element height is unknown or cannot be read directly, you can also set an empty inline label before the element to be centered, assuming <span>, the code is as follows:
span {display:inline-block; width:0; height:100%; vertical-align:Middle}. box{display:inline-block; Vertical-align:Middle}
3. Both horizontal and vertical centering are met:
(1) When the element width and height are known, the position + negative margin is used
(2) The element width and height is unknown or cannot be read directly, and there is no float, you can use the flex layout, after the parent element is set Display:flex, the target child element is directly Margin:auto
(3) for floating elements, you can also use the Flex layout, the code is as follows:
. Container {display:Flex} . Box {justify-content:Center; align-items:Center}
Note: The flex layout is not applicable in the low version of IE, but it is most efficient and convenient to achieve the center effect;
Some people on the net use table and Table-cell layout method, can also achieve the center, but I do not advocate, reason two points: one involves three layers of nesting, and the second is to use table to display the table, instead of the page layout
Center (horizontal + vertical, floating + positioning, fixed width + variable width)