Home  >  Article  >  Web Front-end  >  How to center css code

How to center css code

coldplay.xixi
coldplay.xixiOriginal
2021-03-12 16:30:4923049browse

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.

How to center css code

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.

How to center css code

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.

How to center css code

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.

How to center css code

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.

How to center css code

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.

How to center css code

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.

How to center css code

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn