Methods for centering css code: 1. Positioning method [position:absolute]; 2. Use [margin:auto] method; 3. Use [display:table-cell] method; 4. Use [transform: translate(x,y)] method.
The operating environment of this tutorial: windows7 system, css3 version, DELL G3 computer.
Css code centering method:
1. Positioning method: position:absolute
If the child div is defined This method can be used for width and height. Note: The values of margin-top and margin-left are half of the height and width values. You can try it and see the effect.
2. Margin:auto method
This can also be a positioning method. Using this method requires that the child div must be set to a width value, otherwise it will have no effect~margin:auto is centered horizontally and vertically. If you only set the horizontal centering, you can set it to margin:auto 0; similarly, if you only set the vertical centering, Can be set to margin:0 auto.
3. display:table-cell method
This method is mainly for multi-line text The vertical center alignment of the content. Note: text-align:center sets the horizontal center alignment of the text, and vertical-align:middle sets the vertical center alignment.
4. transform:translate(x,y) method
This is a new attribute in css3. If the child element This method can be used if the width and height values are not set. This can be used when we make adaptive pages.
5. Before, after pseudo-element method
This also centers the child elements vertically. If you still want to center it horizontally, you can use several other methods to achieve it, such as setting margin: 0 auto for the child elements; this will center it both horizontally and vertically.
6. Flex layout method
This method should fully consider the compatibility of the browser. Elements that need to be vertically centered do not need to set width and height values, and can be used in adaptive pages to achieve horizontal and vertical centering.
Related tutorial recommendations: CSS video tutorial
The above is the detailed content of How to center css code. For more information, please follow other related articles on the PHP Chinese website!