Home >Web Front-end >CSS Tutorial >A brief discussion on several methods to achieve vertical centering of elements using CSS

A brief discussion on several methods to achieve vertical centering of elements using CSS

PHPz
PHPzforward
2016-05-16 12:08:572789browse

A brief discussion on several methods to achieve vertical centering of elements using CSS

Use CSS to horizontally center elements. Row-level elements set the text-align center of their parent elements, and block-level elements set their own left. Just set right margins to auto. This article collects six methods of vertically centering elements using CSS, let’s take a look!

Line-Height Method

line height demo
Trial: Single line text vertically centered, demo

Code:

html

<p id="parent">
<p id="child">Text here</p>
</p>

css

#child {
Line-height: 200px;
}

Vertically center an image, the code is as follows

#html

##


css

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

CSS Table Method

table cell demo

Applicable: Universal, demo

Code:

html

Content here


css

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

Lower version IE fix bug:

#child {
Display: inline-block;
}

Absolute Positioning and Negative Margin

absolute positioning and negative margin demo

##Applicable to: block-level elements, demo

code :

html

Content here


css

#parent {position: relative;} #child { position: absolute; top: 50%; Left: 50%; Height: 30%; width: 50%; Margin: -15% 0 0 -25%; }

Absolute Positioning and Stretching

absolute positioning and vertical stretching demo##Applicable: universal, but does not work properly when IE version is lower than 7, demo#

##Code:

html

Content here

css

#parent {position: relative;} #child { position: absolute; top: 0; bottom: 0; left: 0; Right: 0; width: 50%; Height: 30%; margin: auto; }

Equal Top and Bottom Padding

Applicable: Universal, demovertical centering with padding demo

Code:

html

Content here

css

#parent {
padding: 5% 0;
}
#child {
padding: 10% 0;
}

Floater p

Applicable: Universal, demo

Code:

html

<p id="parent">
<p id="floater"></p>
<p id="child">Content here</p>
</p>

css

#parent {height: 250px;}
#floater {
float: left;
height: 50%;
width: 100%;
Margin-bottom: -50px;
}
#child {
Clear: both;
height: 100px;
}

The above are the six methods, which can be chosen reasonably during actual use.

For more programming-related knowledge, please visit:Introduction to Programming! !

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete