CSS implementation of element centering principle analysis

Source: Internet
Author: User

It is a very common requirement to set the horizontal vertical centering of elements in CSS. But it is such a theory that seems to be very simple to achieve, in practice, it often baffled a lot of people.

It is relatively simple to center an element horizontally: if it is an inline element, it is applied to its parent element text-align: center , and if it is a block-level element, it is applied to itself margin: auto .

However, if you want to center an element vertically, it's not that easy, and sometimes just thinking about it makes the scalp numb.

This article from the elements and block-level elements of the description of the current more popular implementation of the collection and analysis of the principle of implementation, convenient for everyone to access. Here to illustrate a point, each way is not perfect, the key to see their own needs, so as to analyze which way of implementation is the most appropriate.

In-line elements

First we write the basic code:

<div    "main"  >  <span   class=   "content"  >  I'm the inline element span to center </SPAN>  </DIV>   
.main{    width:300px;    height:300px;    background-color:#50ba8b;}.content{    background-color:#5b4d4e;    color:#FFFFFF;}

The class .main div wraps this one class-in- .content line element span, and our goal is to have the .content element centered within the .main element.

Horizontal Center Text-align

The horizontal center of the inline element is simple, we add it directly in .main text-align: center; , and it .main becomes:

.main{    width:300px;    height:300px;    background-color:#50ba8b;        text-align:center;  /* 水平居中 */}

implementation principle: set text-align the value to be center , because the attribute specifies the horizontal alignment of the text in the element, then the center text is centered horizontally.

Center vertically Line-height

The vertical center of the inline element is divided 一行 and 多行或者图片等替换元素 explained.

If 一行 So, then we can use it line-height to implement, when the .main element CSS code becomes:

.main{    width:300px;    height:300px;/* 可以不设置 */    background-color:#50ba8b;    line-height:300px;/* 垂直居中 */}

In fact, set up the line-height text can be vertically centered, do not need to set up at the same time height , here is a misunderstanding has always existed.

Implementation principle: this way to achieve vertical centering using the "line spacing of the upper and lower mechanism" in CSS, which also explains why the method only applies to 一行 the text.

It is also necessary to note that the vertical centering of this approach is "approximate", not the perfect vertical center, because the vertical midline position of the text glyph is generally lower than the vertical midline position of the real "line box", and because we usually use the font-size relatively small, making this deviation is not easy to detect , then the senses are seen as vertically centered.

Line-height and Vertical-align

多行或者图片等替换元素The following is the vertical center effect, here we need to use line-height and vertical-align to achieve.

Let the text wrap first:

<div class="main">    <span class="content">        <br>        我是要居中的行内元素span    </span></div>

Then look at the modified CSS code:

. Main {    Width: 300px;    Background-color: #50ba8b;    Line-height: 300px;}. Content {    Display: Inline-block;    Background-color: #5b4d4e;    Color: #FFFFFF;    Line-height: 20px;    margin: 0 20px;    vertical-align: Middle;}

Implementation principle:

    1. .contentthe display of the set element is Inline-block. The function is to reset the external line-height to the normal size, but also to maintain the element characteristics, so that the Vertical-align property can be set, as well as a very critical "line box". What we need is not this "line box", but a product that comes with each "wireframe box"--"Ghost Blank Node", a Invisible "node" with a width of 0 that behaves like a normal character. With this "Ghost blank node", we have an line-height: 300px; object that works, which is equivalent to .content a 0-in-line element with a height of 300px in front of the element.
    2. Because inline elements are baseline aligned by default, we .content adjust the vertical position of multiline text by setting the element to vertical-align: middle; achieve the "vertical centering" effect we want. This method also applies to 图片等替换元素 the vertical centering effect. Of course, the "vertical Center" is also approximate, this is due to the vertical-align, the specific why can be deeply understood vertical-align: middle; .
Block-level elements

Still write the base code first:

<div class="main">    <div class="content">我是要居中的块级元素div</div></div>
.main{    width:300px;    height:300px;    background-color:#50ba8b;}.content{    width:150px;    height:150px;    background-color:#5b4d4e;}

The div wrapped in class is .main a .content block-level element div that is class, and our goal is to have the .content element centered within the .main element.

Position + Margin:auto

The implementation code is as follows:

. Main {    Width: 300px;    Height: 300px;    Background-color: #50ba8b;        / * Key code * /    Position: relative;}. Content {    Width: 150px;    Height: 150px;    Background-color: #5b4d4e;    / * Key code * /    Position: Absolute;    Top: 0;    Left : 0;    Bottom: 0;    Right : 0;    margin: Auto;}

Implementation principle:

    1. Sets the .main element to relative positioning position: relative; so that its child elements are set to the absolute position relative to it.
    2. It then sets .content the element to absolute positioning position: absolute; and sets its top ,, left bottom and all 0, so that the element's right dimensions appear as "formatted width and format height", and <div> the "normal flow width" is the same as the external dimension, That is, the dimensions are automatically populated with the available dimensions of the parent element, but since we set the width of the element at this point .content , the element is automatically populated, so that we have more than 150px of space.
    3. Finally, we set the .content element for margin: auto; , at this time according to auto calculation rules, the left and right of the remaining space all equal, naturally centered.
Position + Margin-left/top

The implementation code is as follows:

. Main {    Width: 300px;    Height: 300px;    Background-color: #50ba8b;        / * Key code * /    Position: relative;}. Content {    Width: 150px;    Height: 150px;    Background-color: #5b4d4e;    / * Key code * /    Position: Absolute;    Top: 50%;    Left : 50%;    Margin-left: -75px;    Margin-top: -75px;}

Implementation principle:

    1. Sets the .main element to relative positioning position: relative; so that its child elements are set to the absolute position relative to it.
    2. Then set the .content element to absolute positioning position: absolute; and set, so that the upper top: 50%; left: 50%; .content -left corner of the element is at the .main center of the element.
    3. Finally, you set the .content element margin-left: -75px; , margin-top: -75px; move it to the left and move it up by half, so that the center of the element is centered on the .content .main element, which naturally results in a center effect.
    4. The disadvantage of this approach is the need .content for a fixed element of the width of the height.
Position + Translate

The implementation code is as follows:

. Main {    Width: 300px;    Height: 300px;    Background-color: #50ba8b;        / * Key code * /    Position: relative;}. Content {    Width: 150px;    Height: 150px;    Background-color: #5b4d4e;    / * Key code * /    Position: Absolute;    Top: 50%;    Left : 50%;    Transform:Translate-50%,-50%);}

Implementation principle:

    1. Sets the .main element to relative positioning position: relative; so that its child elements are set to the absolute position relative to it.
    2. Then set the .content element to absolute positioning position: absolute; and set, so that the upper top: 50%; left: 50%; .content -left corner of the element is at the .main center of the element.
    3. Finally, the set element moves itself to the .content transform: translate(-50%, -50%); left and up by half the width, so that the center of the element is centered on the .content .main element, which naturally results in a center effect.
    4. The advantage of this approach is that the .content width of the fixed element is not required.
Flexbox

The implementation code is as follows:

.main  { width:  300px   height:  300px   background-color:   #50ba8b   /* key code */ display:  flex   .content  { width:  150px   height:  150px   background-color:   #5b4d4e   /* key code */ margin:  auto     

Implementation principle:

    1. Sets the .main element display: flex; .
    2. Then set .content the element to be margin: auto; centered.
    3. This is undoubtedly the best solution, we do not need to set the .content element to absolute positioning, margin: auto naturally can be used for the width of the height, and we do not need to set .content the width of the element, because the Flexbox (telescopic box) is specifically designed for such requirements.
    4. The downside is that the current level of browser support is somewhat lower than other methods.

Another benefit of Flexbox is that it can also vertically center an anonymous container (that is, a text node that is not wrapped by a label). For example, instead of setting the .main element as display: flex; , but setting the .content element to display: flex; , and using the Align-items and Justify-content attributes introduced by the Flexbox specification, we can make the text inside it also be centered (we can .mainelements use the same attributes to .content center element elements, but margin: auto are more elegant than methods and play a fallback role at the same time.

.content{    width:150px;    height:150px;    background-color:#5b4d4e;    /*关键代码*/    display: flex;    align-items:center;    justify-content:center;    margin:auto;}

CSS implementation of element centering principle analysis

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.