To realize horizontal center/vertical center

Source: Internet
Author: User

To realize horizontal center/vertical center

I. horizontal center

1.Text-align: center(Line Element)

Set the text-align: center attribute for its parent element;

2.Margin: 0 auto(Block-level elements)

Set margin: 0 auto for the element itself;

3. fixed element width

Margin position + margin-left

. Ele {position: absolute; width: fixed; left: 50%; margin-left:-0.5 width ;}

Margin position + left: 0; right: 0; margin: 0 auto 

. Ele {position: absolute; width: fixed; left: 0; right: 0; margin: 0 auto ;}

4. The element width is not fixed

✓ Css3-transform

.ele{    position:absolute;      left:50%;      transform:translate(-50%,0);}

Trim css3-width: fit-content (you can set the following attributes for the parent element of the element when float: left is set for the element to be centered)

. Ele-parent {width:-moz-fit-content; width:-webkit-fit-content; width: fit-content; margin: 0 auto ;}
This attribute currently only supports Chrome and Firefox browsers.

️ Flex

.ele-parent{    display: flex;    justify-content: center;}

 

2. Vertical center

1. line-height: eleparent-height

You can set properties for vertical center of a single line of text.Line-height: parent element height

2. fixed element height

Position + margin-top

. Ele-parent {position: relative;}. ele {position: absolute; top: 50%; height: fixed; margin-top:-0.5 ;}

BytesPosition + top: 0; bottom: 0; margin: auto 0

. Ele {position: absolute; height: fixed; top: 0; bottom: 0; margin: auto 0 ;}

3. The element height is not fixed

Invalid vertical-align

.ele-parent{    display:table;}.ele{    display:table-cell;
  vertical-align:middle;}    

✓ Css3-transform

.ele{    position:absolute;    top:50%;    transform: translate(0,-50%);}

BytesFlex

.ele-parent{    display: flex;    align-items:center;}

  

Only these shortcomings can be found. Please criticize and correct them !!!

  

 

Related Article

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.