Vertical centering of elements with CSS

Source: Internet
Author: User
Tags border color

User-aware
Links: https://www.zhihu.com/question/20543196/answer/275464838
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

Description
    • .centerRepresents the element to be centered, .wrap representing the parent element of the element to be centered (the .center element that contains the element).

In order to facilitate the understanding and description of the same:

    • The middle of the text content .wrap is the element that contains the text (for example <i>文字</i> , the I tag is .wrap ).

The text content creates a row box (Line-box) outside, which can be thought of as an inline element (the outer frame is invisible).

    • The text content is contained in a container (' father '), and then the container is centered within another container (' grandfather '), not as the middle of the text content, but in the center of the outer container of the text content (' father ' is centered within ' grandfather ').

    • Note that some cases do not set the element width height, border color/background, can not see the center effect, it does not matter whether the center or not.

For example, if the parent container does not set a background or border, and cannot see whether the child element is centered, the sample code simply writes out the part of the style that the centering method requires .

    • inline elements , to be exact, are non-replaceable (non-replace) inline elements that cannot be set in the vertical direction of margin and padding, and do not repeat. (margin)

See margin rules and padding regulations, the reason why margin/padding cannot be set up is because

The value of the padding is calculated based on the width of the target element, while the width of the non-replace element in inline is indeterminate.

    • CSS compatibility situation is not described, the specific self-access caniuse.
    • It is recommended to use a method that does not have to use the exact numeric value, such as 50px,20rem, except for the percentage value of 50%.

Center of inline content

How to center a container's inline content (text and inline element--inline/inlineblock). (Of course inline-block is more special, that is, there are inline attributes, and block-level attributes)

Text-align:center Horizontal Center

Set on a block-level element text-align:center , its inner inline or inline-block child elements, and the text content are centered within the parent element.

Line-height Vertical Center

Line-height sets the distance (row height) between the rows, and the line-heigth value of the element to be centered is set to the same height as its block-level parent element , and its internal content is centered vertically.

Vertical centering of inline elements for a single line

.wrap{  height:100px; line-height: 100px;}

Attention:

    • Line-height cannot use negative values
    • Using Line-height in a block-level element is the minimum distance, not the maximum, that defines the baseline of the element.
Vertical-align:middle Vertical Center

The use effect of vertical-align is divided into the following different situations:

    • Center of inner content in inline element inline/linline-block/inline-table

Use pseudo-elements (also .wrap the parent and sibling elements can be centered, the following code to .wrap::before replace .wrap the sibling element selector)

. Wrap{Display:Inline-Block;Vertical-align: middle;} .wrap::before{// ::after content: display: inline-block height: 100%display:inline-block vertical-align: middle;}      

Attention:

    • Vertical-align most of the values are relative to the parent element

For example vertical-align:baseline (the default value of Vertical-align) is the baseline alignment relative to the parent element. The baseline value of the parent element has the following rules:

    • Inline class-The bottom of the lowercase letter X
    • Inline-block class with no inline type--bottom of box model
    • Inline-block class with inline type-the baseline of the last line of inline elements (that is, the bottom of the last row, lowercase x)

    • set to middle is not necessarily true alignment , and the median position of some fonts is not necessarily the middle of the top and bottom.
    • Different styles of fonts often have different typographic standards, so there are different baselines/midline/top lines, etc., and a variety of font mixes will change the baseline (see the parent element's baseline value rule).

    • Table cell (Table-cell) Element

Set on a cell vertical-align:middle and its internal content is centered vertically.

    • ::first-letterand ::first-line pseudo elements (same as the first inline element)
block-level element centering

How blocks, List-item, Inline-block, and so on, are centered within their parent elements.

margin/padding Value Setting Center

The most basic method is to set the exact padding (on the parent element) or margin (on the child element) value so that the child element is centered, no longer an example.

Clac Calculating Values

The margin value is 50% of the parent container's width/height minus 50% of its width/height:

.center{  width: 20rem;height: 20rem; margin-left:calc(50% - 10rem); margin-top:calc(50% - 10rem);}

Note: The inline horizontal element margin/padding setting is only valid in the left and right directions .

margin:0 Auto Center around

The block-level element element setting to center margin:0 auto .

Note: invalid elements for floating elements, absolute positioning, and fixed positioning . (Note: The four-direction value used in the absolute positioning + offset 0+margin:auto method is a 0 offset exception)

Report:

Note margin/pading

The
percent value is calculated by referencing the width of its containing block

Therefore, it is margin:auto not possible to use the center vertically, and it is best not to use vertical centering margin/pading . (Of course, if you know exactly the height of the parent container, use an exact margin/pading value to implement the column that is no longer discussed)

Position:absolute Center

Set the positioning on the parent element, and then center with absolute positioning on the child element to be centered.

The most basic method: Calculate the difference between the width of the element to be centered and the height of the parent container, then divide the difference by 2 to get the exact value, and then set the exact horizontal and vertical offsets;

The second is to set the horizontal and vertical offset of the pigeon 50%, then set the horizontal and vertical negative margin values-the value of the sub-element to be centered on the width of the half of the height.

All of the above methods need to use the exact value of container width and height, the flexibility is poor, the following methods are more flexible:

offset 50%+ negative margin value

Set the horizontal and vertical offsets for 50%, and then set the Margin-top and Margin-left values to be the negative numbers that are half the width/height of the center element:

. Wrap{position: relative;} .center {position: absolute< Span class= "P"; height: 100px; Width:100pxtop: 50%; Left:50%margin-top:-< span class= "M" >50pxmargin-left:-< span class= "M" >50px;}      
offset 50%+ Negative 50%translate value

Using displacement transform:translate, the child element with the 50% offset is shifted back to half its width:

.wrap {  position: relative;}.center { position: absolute; top: 50%;left:50%; transform: translate(-50%,-50%);}
offset 0+margin:auto

The parent element sets relative or absolute positioning, the child element to be centered is set absolute positioning, all offsets are 0, and the margin is auto:

.wrap{  positon:relative;}.center{ positon:absolute; top:0;bottom:0;left:0;right:0; margin:auto;}
Flex Flexible Layout Center

The parent element is set to the elastic box (container), and the child element becomes the elastic element, which is centered with the flex-related attributes.

    • Setting the correlation property on the parent element centers the child elements:
.wrap{  display:flex; /*使用flex盒子*/ justify-content:center;/*水平轴上居中*/ align-items:center;/*垂直轴上居中*/}
    • The parent element is set to the elastic container display:flex , and the child element is set magrin:auto :
.wrap{  display:flex;}.child{ margin: auto;}

Attention:

    • If there are multiple elastic child elements, the elastic child elements are distributed horizontally in the parent element container by default, because
    1. Flex arranges child elements horizontally into one row () by default flex-direction:row , using the ability to align flex-direction:column child elements vertically into a single column.
    2. The flex default child element does not wrap the row display ( flex-wrap: nowrap ), which flex-wrap: wrap enables the child element to be displayed automatically (multiple rows/columns are broken when the line width/height is insufficient to accommodate multiple child elements).

    • align-itemsand align-content differences:
      • align-contentThe property only applies to flex containers with multiline child elements (more than one row), which does not work if there is only a single row of child elements, and align-items applies to containers for any child element of the row flex .
      • align-contentis to set the way in which a column of child elements are aligned on the entire vertical axis, and to align-items set the alignment (vertical alignment) of each child element on the side axis in the height range of the row.

align-itemsEquivalent to dividing the height of the side axis by the line, setting the way the child element is on the height of the line.

Object-fit and Object-postion Center

Object-fit can only be used with replaceable elements (replaced element) to

specifies how the contents of the replacement element should fit into the box that determines the height and width of its use.

Generally used as a picture style. It has a similar background-image usage:

.center{    object-fit:fill|cover|contain|none|scale-down;/*其属性值,分别是填充(默认)、包含、覆盖(可能被裁剪)、无变化(保持原状)和等比例缩放*/}

The default value of the Object-positon property is 50% 50% , that is, centering (that is, it is not necessary to write this property in the case of centering) ... ), for element positioning control, similar to Background-postion.

grid Grid layout centered

If you want to layout the grid, the element that will be centered is "placed" in the middle of the grid.

Example makes a 3x3 table with elements centered inside:

. Wrap{Display:Grid;Grid-Template -rows: repeat ( 31fr); grid-template-columns : repeat (31< span class= "n" >fr); }.center{grid- row: 2grid-column: 2               /span>                 

Center Table Content
    • Tabular layout: According to the semantic principle, the use of table layout is no longer suitable for table content, and the table <td> <th> label align and valign property is already an HTML revocation tag attribute, it is recommended not to use .
    • Non-tabular element simulation table: You can use display:table-cell to simulate it as a table, because it is not recommended to use the abolished align and valign tag properties, it is also vertical-align:middle useful for vertical centering, it is not important to simulate the element into a table vertically, it is not recommended to use .
    • The real table, the center of the table content :
      • Level:text-align:center
      • Vertical:vertical-align:middle
      • You can also use other methods, such as margin/pading, to control the center of table content

Vertical centering of elements with CSS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.