Enhance the fight against white diary - the level of child elements vertically centered in the parent element

In some page layout, while the sub-element is centered in the vertical and horizontal direction are we more common form of operation, today share a few more convenient way for everyone. For example, we take the parent element of the cube 600px, 300px by sub-element width, high 200px.
1. In the case of taking a fixed size sub-element locating method of the pulled +
we first use the absolute positioning position: absolute;top: 50%;left: 50%;(plus the relative positioning of the parent element, it is easy to ignore white) child element of the parent element is located in the center of the upper right corner, and then margin:-“子元素宽度和高度的一半”making the sub- the center point of the elements located in the center point of the parent element. This method is not very intelligent, there are limitations in the width and height of a child element of uncertainty situation.

position: absolute;top: 50%;left: 50%;
margin: -100px -150px;

2. positioning + displacement
margin: ##% relative to the parent element is displaced translate(##%)with respect to child elements, just to compensate for the drawbacks of a method.

position: absolute;top: 50%;left: 50%;
transform: translate(-50%,-50%);

Here Insert Picture DescriptionHere Insert Picture Description
3. characterized using analytical code, is cumbersome, is not recommended

position: absolute;top: 0;left: 0;bottom: 0;right: 0;
 margin: auto;

margin;auto; Alone to write only the middle level, when using position: absolute;top: 0;left: 0;bottom: 0;right: 0;, the child elements from the document flow, this time, margin;auto;you can achieve the middle child elements.
4. Flex elastic layout (simple, recommended)
by the elastic box, margin:auto;the characteristics of the up and down will take effect, added to the parent elementdisplay:flex;

 #box{width:600px;height: 600px;border: black 1px solid;margin: 100px auto;display: flex;}
 #box div{background: blue;height: 200px;width: 300px;margin: auto;}

FIG effect ↓ ↓ ↓
Here Insert Picture Description

Released five original articles · won praise 6 · views 519

Guess you like

Origin blog.csdn.net/vitasAA/article/details/104584714