6 ways to center CSS elements vertically

Source: Internet
Author: User

The use of CSS for the horizontal center of elements, relatively simple, row-level elements set its parent element of the Text-align Center, block-level elements set its own left and right margins for auto. This paper collects six methods of vertical centering of elements using CSS, each of which is suitable for different situations and chooses a certain method in the actual use process.

Line-height Method


Trial: Vertical centering of single-line text

Code:

Html

<div id="parent"><div id="child">text here</ Div></div>

Css

#child {line-height:200px;}

Center a picture vertically, the code is as follows

Html

<div id="parent"><img src="image.png " alt= "" /></div>

Css

#parent {line-height:200px;} #parent img {Vertical-align:middle;}

CSS Table Method

Applicable: Universal

Code:

Html

<div id="parent"><div id="child">content here </div></div>

Css

#parent {display:table;} #child {display:table-cell;vertical-align:middle;}

Low version of IE fix bug:

#child {display:inline-block;}

Absolute positioning and negative Margin

For: block-level elements

Code:

Html

<div id="parent"><div id="child">content here </div></div>

Css

 % of the 0 0 -%;}

Absolute Positioning and stretching

Applicable: general, but not working correctly when IE version is below 7

Code:

Html

<div id="parent"><div id="child">content here </div></div>

Css

0000% ; margin:auto;}

Equal Top and Bottom Padding

Applicable: Universal

Code:

Html

<div id="parent"><div id="child">content here </div></div>

Css

5 0  0;}

Floater Div

Applicable: Universal

Code:

Html

<div id="parent"><div id="floater"></div ><div id="child">content here</div></div>

Css

#parent {height:250px;} #floater {float%; margin-bottom:- 50px;} #child {clear:both;height:100px;}

The above is six kinds of methods, can be used in the actual process of reasonable choice, reference to the article "Vertical-centering".

6 ways to center CSS elements vertically

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.