gpt4 book ai didi

css - 以未知高度居中响应 div 并启用完全垂直滚动

转载 作者:行者123 更新时间:2023-11-28 16:45:36 25 4
gpt4 key购买 nike

我试图将高度未知的 div 居中。

当视口(viewport)高度小于 div 高度时,我找不到允许滚动到 div 顶部的解决方案。

HTML

<div>
<p>This will be hidden when <br />
window_height < div_width</p>
<br />
<br />
<br />
How to make it scroll to the top?
</div>

CSS

    body {
background: grey;
}
p{
background: green;
}
div {
position: absolute;
left: 50%;
top: 50%;
box-sizing: border-box;
transform: translate(-50%, -50%);
max-width: 500px;
width:100%;
height: 700px; /* Unknown*/
padding: 20px;
background: red;
color: white;
text-align: center;
}

http://codepen.io/Koopa/pen/GpypdX

谢谢

最佳答案

您无法滚动到 div 顶部的原因是因为具有负值的 transform 属性将 div 定位为关闭 -在较小的屏幕上显示。

在此演示中,transform 被禁用:
http://codepen.io/anon/pen/wKpMyM

另外,当你对一个元素应用绝对定位时,你会把它从 normal flow 中取出来。的文件。这意味着它被它的容器忽略了。因此,bodyhtml 元素的高度为零。

在这个演示中,body 有一个绿色边框(完全折叠):
http://codepen.io/anon/pen/RWxrod

为了让你的布局工作,你可以给 body 一个最小高度(这样它可以随着 div 展开)并且,而不是用绝对定位居中,使用flexbox .

CSS

html { height: 100%; } /* necessary for percentage heights to work */

body {
background: grey;
border: 10px solid green; /* for demo purposes */
min-height: 100%; /* allow body to expand with children */
display: flex; /* establish flex container */
justify-content: center; /* center div horizontally, in this case */
align-items: center; /* center div vertically, in this case */
}

p {
background: green;
}

div {
/* REMOVE
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); */

box-sizing: border-box;
max-width: 500px;
width:100%;
height: 700px; /* Unknown*/
padding: 20px;
background: red;
color: white;
text-align: center;
}

演示:http://codepen.io/anon/pen/OyzMvV

注意所有主流浏览器都支持 flexbox,except IE 8 & 9 .

关于css - 以未知高度居中响应 div 并启用完全垂直滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33225614/

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