How to achieve horizontal/vertical centering?

Center horizontally

1. Elements in the line

If the set element is an inline element such as text or image, horizontal centering is achieved by setting
text-align:center to the parent element

2. Fixed-width block elements

When the set element is a block element, using text-align: center will not work. Elements that meet the two conditions of fixed width and block shape can be centered by setting the "left and right margin" value to "auto".

3. Indefinite width block element 1

1) Add a table tag (including,,) outside the centered element to be set.

2) Set the "left and right margins to the center for this table.
Insert picture description here
Insert picture description here
4. Unfixed width block element 2

Change the dispaly of the block-level element to inline type, and then use text-align:center to achieve the centering effect
Insert picture description here
Insert picture description here
5. Indefinite width block element 3

By setting float to the parent element , then setting position:relative and left:50% for the parent element , and setting position:relative and left:-50% for the child element to achieve horizontal centering
Insert picture description here
Insert picture description here

Vertically centered

1. Single line of text with the height of the parent element

The vertical centering method is achieved by setting the height of the parent element to be consistent with the line-height height.
Insert picture description here
Insert picture description here
2.
Speaking of vertical centering, there is an attribute vertical-align in css for vertical centering, but this style is only in the parent element It will take effect when it is td or th

3. Multi-line text with the height of the parent element 1

Use insert table (including tbody, tr, td) tags, and set vertical-align: middle (because the td tag defaults to set vertical-align to middle by default, so we don’t need to explicitly set it)
Insert picture description here
Insert picture description here
4. Parent Multi-line text with determined element height 2

You can set the display:table-cell, vertical-align:middle of block-level elements in chrome, firefox and browsers above IE8, but note that IE6 and 7 do not support this style.

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/zzDAYTOY/article/details/108268481