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;
}
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.
demo: http://codepen.io/gc-nomade/pen/pubFm
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 negativetop-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:Alternatively, you can use a combination of
display: table
and thendisplay: table-cell
on the parents to open up the ability to usevertical-align
although this is a bit nasty when it comes to laying out elements around it.Use
display: table
for the parent div, anddisplay:table-cell; vertical-align: middle
for the content div which you want to vertically center.