CSS垂直对齐div,同时保持宽高比 [英] CSS vertically align div while maintaining aspect ratio

查看:94
本文介绍了CSS垂直对齐div,同时保持宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 jsfiddle.net/5tzk3/10 上使用了JsFiddle.我将其更改为将div显示为方形对话框(水平居中和垂直居中).结果为 jsfiddle.net/5tzk3/548 .

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.

如您所见,水平居中很容易,但我无法使其垂直居中.有谁知道如何使用纯CSS做到这一点?

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?

下面的编辑代码:

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

推荐答案

对于父div使用display: table,对于要垂直居中的内容div使用display:table-cell; vertical-align: middle.

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

这篇关于CSS垂直对齐div,同时保持宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆