When writing CSS styles, sometimes you may encounter difficult problems for the sake of appearance, such as flat water and vertical center, some horizontal and vertical center attributes are completely unresponsive. The following lists some ultimate solutions for CSS horizontal and vertical center:
I. Horizontal center of CSS
There are roughly three cases of horizontal center of css:
1. Text, images, and other line elements:
Add attributes to the parent element: text-align: center;
2. Block-level elements that determine the width:
Add attributes: margin-left: auto; margin-right: auto;
3. Block-level elements with uncertain width:
There are three solutions:
A. Convert the block-level element display: inline; into a row element and use text-align: center to implement it.
B. Include block-level elements in the table, and add the attribute margin-left: auto; margin-right: auto to the table;
C. Set float for the parent element, set position: relative; left: 50% for the parent element, and set position: relative; left:-50% for the child element.
II. Vertical center of CSS
Css vertical center also has three situations:
1. The height of the parent element is determined. Single line text:
You can set the line-hight value to be equal to its height value;
2. Multiline text and images with the parent element height determined:
Two solutions:
A. Include them in table labels. By default, td labels have the vertical-align: middle attribute;
B. Add attributes to the parent element: display: table-cell; vertical-align: middle;
3. Text and images with uncertain parent elements:
Set the same top and bottom margins for the parent element: padding-top: 10px; padding-bottom: 10px;
For IE6/7 with brain damage, you may need to add hack separately. Set position: absolute; top: 50%; for the parent element, set position: relative; top:-50%;