Horizontally aligning a div-element within another div-element can be achived with margin: 0 auto;
as long as they both have a width-property other than auto
, but this does not apply for vertical alignment.
How can you vertically align a div within another div?
There are a number of different approaches to this, based on various ideas. Given that the element has a fixed height (in px, % or what have you), the best solution I've found so far is based on the following principle:
Give the parent div position: relative;
and the child div position: absolute;
, to make the child absolutley positioned in relation to the parent.
For the child, set top
, bottom
, left
and right
to 0
. Given that the child also has a fixed width
and height
that is less than the size of the parent, this will push the browser into an impossible situation.
In comes margin: auto;
on the child, as the browsers savior. The browser can now add enough margin on all sides to let the child-element keep its size, yet still fill out the entire parent as forced by top
, bottom
, left
and right
set to 0
.
TADAAA! The element gets vertically and horizontally aligned within the parent.
Markup
<div class="parent">
<div class="child"></div>
</div>
CSS
.parent {
width: 200px;
height: 200px;
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
}
A working example
I find it easiest to use display:table-cell; vertical-align:middle;
display:table-cell; vertical-align:middle;
here's a jsfiddle
<style>
.a {
border:1px solid red;
width:400px;
height:300px;
display:table-cell;
vertical-align:middle;
}
</style>
<div class="a">
<div>CENTERED</div>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.