垂直居中一个可变高度的div在作为视口的100%的div内 [英] Vertically center a div with variable height within a div that is 100% of the viewport

查看:161
本文介绍了垂直居中一个可变高度的div在作为视口的100%的div内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它看起来像一个问题,已被问过很多次,但我只是找不到解决方案,这个非常具体的情况。



这里的基本我的布局的线框:





基本上,我有一些不同背景的div,它们占用浏览器窗口的100%宽度和100%高度。在每个和每一个都是另一个div,它占据其父的50%宽度,但具有可变的高度,根据其内容。



我想所有这些divs-within-a-div垂直对齐。
现在,我已经读过,放一个显示:table-cell和vertical-align:middle在父应该工作,但在这种情况下,它只是似乎混乱的东西。 : - /



我的代码:

 < head& 
< style>
html,body {
height:100%;
}
body> div {
width:100%;
height:100%;
background-size:cover;
}

。center {
width:50%;
margin:0 auto;
background:rgba(0,0,0,0.4);
padding:50px 0 30px 0;
}
< / style>
< / head>
< body>

< div id =pic_1>
< div class =centered> content< / div>
< / div>

< div id =pic_2>
< div class =centered> content< / div>
< / div>

< div id =pic_3>
< div class =centered> content< / div>
< / div>

< / body>

感谢您的帮助!

解决方案

设置一个祖父元素为 display:table; height:100%,父元素为 display:table-cell;请参阅方法1

此外,请注意,您的标记不应使用 class =centered ;请使用语义类名称。


I know it looks like a question that has been asked many times, but I just couldn't find the solution to that very specific situation.

Here's the basic wireframe of my layout :

Basically, I've got a few divs with different backgrounds that take 100% width and 100% height of the browser window. Within each and every of them is another div that takes 50% width of its parent but has a variable height, depending on its content.

I'd like all of these divs-within-a-div to be vertically align. Now, I've read that putting a display:table-cell and a vertical-align:middle on the parent should work, but in this case it just seems to mess things up. :-/

My code:

<head>
<style>
     html, body {
            height: 100%;
        }
        body > div {
            width: 100%;
            height: 100%;
            background-size: cover;
        }

        .centered {
            width: 50%;
            margin: 0 auto;
            background: rgba(0,0,0,0.4);
            padding: 50px 0 30px 0;
        }
</style>
</head>
        <body>

            <div id="pic_1">
                    <div class="centered">content</div>
            </div>

            <div id="pic_2">
                    <div class="centered">content</div>
            </div>

            <div id="pic_3">
                    <div class="centered">content</div> 
            </div>  

        </body>

Thanks for your help!

解决方案

Set a grandparent element to be display:table; height:100% and the parent element to be display:table-cell; vertical-align:middle.

See "Method 1" here for an example.

Also, note that your markup should not use class="centered"; use a semantic class name instead.

这篇关于垂直居中一个可变高度的div在作为视口的100%的div内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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