gpt4 book ai didi

css - 一个 div 可以用基于像素的边距填充整个视口(viewport),而不使用 CSS3 calc 属性吗?

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

我找到了一种(hacky)方法让 div 占据浏览器的整个视口(viewport),减去基于像素的边距,通过像这样使用 CSS3 calc 属性(参见 fiddle ):

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

div {
background: linear-gradient(red, yellow);
height: calc(100% - 26px);
margin: 13px 0 0 13px;
width: calc(100% - 26px);
}
<body>
<div></div>
</body>

是否可以仅使用 CSS 2.1 属性来做同样的事情?我知道大多数浏览器已经支持 calc 很长一段时间了,但它是 also looks like the most popular polyfills have their limitations 。我一直在努力寻找更优雅的解决方案 - 例如,我不必使用 overflow:hidden 锁定超大视口(viewport)的解决方案。如果不使用 calcvh/vw 单位,这似乎几乎是不可能的。

最佳答案

对于宽度,您不需要做任何事情,因为默认情况下它会占用所有空间。对于高度,您可以考虑在 body 上填充并使用 height:100%

html,
body {
height: 100%;
margin: 0;
overflow: hidden;
}
body {
padding: 13px 0;
box-sizing:border-box;
}
div {
background: linear-gradient(red, yellow);
height: 100%;
margin: 0 13px;
}
<body>
<div></div>
</body>

或者在所有边上无边距填充:

html,
body {
height: 100%;
margin: 0;
overflow: hidden;
}
body {
padding: 13px;
box-sizing:border-box;
}
div {
background: linear-gradient(red, yellow);
height: 100%;
}
<body>
<div></div>
</body>

或者一个固定的元素,你不必费心在 body/html 上设置宽度/高度

body > div {
position:fixed;
top:13px;
left:13px;
bottom:13px;
right:13px;
background: linear-gradient(red, yellow);
}
<body>
<div></div>
</body>

也可以考虑使用透明边框:

html,
body {
height: 100%;
margin: 0;
overflow: hidden;
}
div {
background: linear-gradient(red, yellow) padding-box;
height: 100%;
border:13px solid transparent;
box-sizing:border-box;
}
<body>
<div></div>
</body>

关于css - 一个 div 可以用基于像素的边距填充整个视口(viewport),而不使用 CSS3 calc 属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54768085/

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