CSS vertically align div while maintaining aspect

2019-09-16 17:59发布

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; 
}

3条回答
祖国的老花朵
2楼-- · 2019-09-16 18:32

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

查看更多
你好瞎i
3楼-- · 2019-09-16 18:41

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.

查看更多
Deceive 欺骗
4楼-- · 2019-09-16 18:58

Use display: table for the parent div, and display:table-cell; vertical-align: middle for the content div which you want to vertically center.

查看更多
登录 后发表回答