问题
I used the JsFiddle at jsfiddle.net/5tzk3/10. I changed it to display the div as square shaped dialog (both horizontally and vertically centered). The result is at jsfiddle.net/5tzk3/548.
As you see, centering horizontally was easy, but I could not get it centered vertically. Anyone who knows how to do that with pure CSS?
Edited code below:
<div class="blind">
<div class="wrapper">
<div class="main">
I'm your div with an aspect-ratio of 1:1!
</div>
</div>
</div>
html, body, .blind {
height: 100%;
width: 100%;
}
.blind {
left: 0;
position: fixed;
text-align: center;
top: 0;
}
.wrapper {
display: inline-block;
margin: auto;
position: relative;
width: 50%;
}
.wrapper:after {
content: '';
display: block;
padding-top: 100%;
}
.main {
background-color: rgb(0, 162, 232);
bottom: 0;
left: 0;
margin: auto;
position: absolute;
right: 0;
top: 0;
}
回答1:
Use display: table
for the parent div, and display:table-cell; vertical-align: middle
for the content div which you want to vertically center.
回答2:
The most common way of doing this if you've got an element with known dimensions is to use positioning to firstly position it top: 50%
(which places the top edge of the element 50% of the way down) and then use a negative top-margin
of half the height of the element (pulling it back up by half it's height).
To give you an example, to absolutely position a 200x200
element dead-centre on the page you would use:
.element{
display: block;
width: 200px;
height: 200px;
position: absolute;
top: 50%;
margin-top: -100px
}
Alternatively, you can use a combination of display: table
and then display: table-cell
on the parents to open up the ability to use vertical-align
although this is a bit nasty when it comes to laying out elements around it.
回答3:
you can drop absolute positionning and use either display:table or inline-block with pseudo elements.
here is a mixed of the 2 methods
1) html/body as a table one cell 2) inner content with ratio preserved and content as inline box set in the middle.
.ratio1-1 {
width:25%;
vertical-align:middle;
margin:auto;
background:turquoise;
}
.ratio1-1:before {
content:'';
padding:50% 0;
width:0;
display:inline-block;
vertical-align:middle;
}
.ib {
display:inline-block;
vertical-align:middle;
}
/* center body content as a table cell */
html {
height:100%;
width:100%;
display:table;
}
body {
display:table-cell;
vertical-align:middle;
text-align:center;
}
<div class="ratio1-1">
<div class="ib">content in middle</div>
</div>
demo: http://codepen.io/gc-nomade/pen/pubFm
来源:https://stackoverflow.com/questions/20315493/css-vertically-align-div-while-maintaining-aspect-ratio