CSS vertical horizontal center, css vertical center

Source: Internet
Author: User

CSS vertical horizontal center, css vertical center

By summarizing the basic methods of horizontal center and vertical center, the method of combing vertical horizontal center is not so messy.

  • Text-align: center + line-height

For example, in div2, text-align + line-height is used to center a single line of text horizontally and vertically.

 

You can also set div2 to inline-block to implement vertical and horizontal center of the div.

 
  • Text-align: center + vertical-align: middle

To center div2 in div1, you need to set the parent element to text-align: center, because the center effect is only valid for text content and in-row elements, then we set the sub-element div2 to the inline-block element, and set the parent element to the table-cell element, vertical-align: middle,

 
  • Margin: 0 auto + vertical-align: middle

Margin: 0 auto; it can be set on its own element to realize horizontal center of block-level elements, so set the child element to margin: 0 auto; set the parent element to the table-cell element, and vertical-align: middle.

 
  • Absolute positioning achieves vertical and horizontal center

Absolute positioning element vertical and horizontal center: Because absolute positioning elements are 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. At this time, if we set the width to a fixed value and the margin to auto, as long as the left and right values are equal (or both are 0 ), the horizontal center can be achieved if the value does not exceed half of the width of the relative element minus the absolute positioning element. The same is true for vertical center, as long as the value of top and bottom is equal or both 0, so that our absolute positioning element achieves vertical and horizontal center.

 

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.