Vertical center Method in CSS, vertical center Method in CSS
Yesterday I summarized the method of water in css. Today I will summarize the method of vertical center in css.
Line-height is used to vertically center a single line of text. For example, to vertically center a single line of text, you only need to set div2 to have the same line-height and height values, you do not need to set the height, because the Row Height of a single line of text will open the height. In fact, the two are the same values.
However, this method has a disadvantage, that is, if the length of the text content is greater than the block width, some content is separated from the block, because it is no longer a single line of text, therefore, this method only applies to single-line text.
Another method is to wrap the content of the element without setting the element height. In this case, you only need to set the padding-top and padding-bottom to the same value, the same is the vertical center effect, and this method is applicable to multiple lines of text.
Vertical-align: middle can also be vertically centered, but it has the following situations:
For example, when div2 has both inline and inline-block elements, the height of div2 is supported by the image height, and the image and text are displayed in one row, however, we found that there is a gap below the image, because inline-block comes with the vertical-align attribute and is the default baseline. Now we set vertical-align to middle, and the vertical center is displayed. (The vertical-align attribute only applies to html elements with the valign feature, such as <td> <th> in table elements, but elements like <div> <span> cannot .)
But when we set the height for div2, vertical-align: middle does not work. You can add inline-height.
When the container only contains text without images, you can use display and vertical-align to vertically center the text in the container. By setting the display of the parent element to table-cell and vertical-align: middle, the child elements can be vertically centered, this is similar to the vertical center of cells in the table.
Add a baseline element before div2, set its height to half the height of the parent element, and then set the size of the margin-top value to negative for the element to be vertically centered, when line-height is set, vertical center is implemented.
- Absolute positioning achieves vertical center
Because the absolute positioning element is scalable, if we set the width of the absolute positioning element to auto, and set left and right to 0, then the element is filled with its parent element horizontally. In this case, if we set the height to a fixed value and margin to auto, as long as the top and bottom values are equal (or both are 0 ), the vertical center can be achieved if the value does not exceed half of the height of the relative element minus the absolute height of the positioning element.