gpt4 book ai didi

html - 嵌套 100% 高度

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:43 25 4
gpt4 key购买 nike

我正在开发一个结构如下所示的移动网站:

body
---->Mobile container div (height 100%)
-------->Full page div (height 100%)
------------>Vertically centered div (height 200px)

我的问题是整页 div 级别显示为 0px。这是相关的 CSS:

html, body
{
height: 100%;
margin: 0;
}

.mobile
{
min-height: 100%;
}

.full-page
{
height: 100%;
position: relative;
}

.center
{
height: 200px;
top: 50%;
margin-top: -100px;
position: absolute;
}

移动容器填充了窗口高度,但整个页面(移动容器高度的 100%)以 0 像素高度呈现,这破坏了垂直居中。

为什么会这样?


JSFiddle

  • 红色的div是移动容器
  • 黄色的 div 是整个页面的 div(它不可见,因为它的高度为 0px)
  • 绿色的div是垂直居中的div

最佳答案

这是由于以下规则而发生的:

.mobile {
min-height: 100%;
}

这就是原因。

CSS specs告诉我们以下有关百分比高度的信息:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto. A percentage height on the root element is relative to the initial containing block.

这适用于您的 .fullpage 容器。您可以看到 .fullpage 的父容器,即 .mobile,没有明确设置高度,而是通过 min-height 属性设置的:

The min-height property is used to set the minimum height of a given element. It prevents the used value of the height property from becoming smaller than the value specified for min-height.

您可能认为子容器 .fullpage 在确定其高度时会考虑 min-height 属性,但事实并非如此。如果仅使用最小高度,浏览器将不会根据其父元素的计算高度来设置子元素的高度(以百分比指定)。

要更正此问题,您可以将 height: 100% 添加到:

.mobile {
min-height: 100%;
}

关于html - 嵌套 100% 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36726805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com