【问题标题】:Can parent and child height both be in percentage?父母和孩子的身高可以都是百分比吗?
【发布时间】:2014-01-08 19:58:10
【问题描述】:

我正在尝试将图像完全填充到设备的全屏。所以我给了.container:100% 和 body,html 到 100% 的高度。现在我想将child div 垂直居中对齐,无论它有什么内容,但它应该垂直居中。所以我尝试在margin-topbottom 上都给出50% height25%。所以正好 100% 它应该符合计算。但这并没有像预期的那样发生。

为什么它没有垂直居中?换句话说,为什么 div 的顶部和底部没有相等的空间,即使我用height:50%; 给出了相等的顶部和底部边距

如何垂直居中对齐?不应该有垂直滚动条,因为我将 body,html.container 的高度设置为 100%,但它正在出现。

CSS

.child{    
    width: 100%;
    height: 50%;
    margin-top: 25%;
    margin-bottom: 25%;
    background-color: red;
    color:white;
}
html,body,.container{
    width:100%;
    height:100%;
    background:url('http://cdn.morguefile.com/imageData/public/files/e/earl53/
                   preview/fldr_2009_05_25/file5821243281047.jpg');
    background-size:cover;

}

HTML

<div class="container">
    <div class="child">
        Hello i(red color div) should be cenetered in vertical direction
    </div>
</div>

JSFIDDLE

【问题讨论】:

标签: html css


【解决方案1】:

百分比边距根据容器的宽度计算see here

百分比是指包含块的宽度

(指边距)

因此,您不能在 CSS 中使用垂直居中的边距(除非您为容器和子级设置了固定高度)。


实现您的目标

您可以使用绝对定位

子元素垂直居中的CSS:

position:absolute;
top:25%;
left:0;
height:50%;
width:100%;

FIDDLE

在这个小提琴中,我还通过添加

使滚动条消失
body,html{
    margin:0;
    padding:0;
}

【讨论】:

  • 如果我添加内容。其他的东西都在 div 的顶部。搞砸了
  • 你的意思是div的高度必须适应它的内容?
  • 我正在尝试在 bootsrap 中使用它
  • 现在怎么对齐居中了?这里的关键是什么?
  • 两个 div 应该并排居中对齐
【解决方案2】:

除了缺少:

margin:0;
padding:0;

html, body, .container

在我看来非常集中...http://jsfiddle.net/5LMY7/

或者……

如果您可以修复child 的高度,那么您可以使用calc 来帮助您:

    .child {
    width: 100%;
    height: 50px; /* assuming fixed height */
    margin-top: calc(50% - 50px);
    margin-top: -moz-calc(50% - 50px);
    margin-top: -webkit-calc(50% - 50px);
    background-color: red;
    color:white;
}

【讨论】:

  • 尝试将窗口/框架调整为太小。
  • 对...即使使用calc 也会出现此问题...。不想使用position!!
【解决方案3】:

试试这个代码:

Fiddle

body
{
    margin: 0px;
    padding: 0px;

}

.child{    
    width: 100%;
    height: 50%;
    top: 25%;
    bottom: 25%;
    background-color: red;
    color:white;
    position:absolute;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-27
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    相关资源
    最近更新 更多