div是否可以使用基于像素的边距填充整个视口,而不使用CSS3 calc属性? [英] Can a div fill up the entire viewport with a pixel-based margin, not using the CSS3 calc property?

查看:55
本文介绍了div是否可以使用基于像素的边距填充整个视口,而不使用CSS3 calc属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一种(巧妙的方法)通过使用CSS3 calc 使div占据浏览器的整个视口,减去基于像素的边距。像这样的属性(请参见小提琴):

I've found a (hacky) way to have a div take up the full viewport of a browser, minus a pixel-based margin, by utilizing the CSS3 calc property like so (see 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已经被大多数浏览器支持了一段时间了,但是看起来也像最受欢迎的polyfill有其局限性。我一直在努力寻找一种更优雅的解决方案,例如,我不必通过 overflow:hidden 锁定超大视口的方法。如果不使用 calc vh / vw 似乎几乎不可能做个单位。

Is it possible to do the same thing with only CSS 2.1 properties? I know calc has been supported in most browsers for quite some time but it also looks like the most popular polyfills have their limitations. I have been beating my head against the wall trying to find a more elegant solution - for instance, one where I don't have to lock down the oversized viewport with overflow:hidden. It seems close to impossible to do without the use of calc or vh / vw units.

推荐答案

对于宽度,您无需执行任何操作,因为默认情况下它将占用全部空间。对于身高,您可以考虑对身体进行填充,并使用 height:100%

For the width you don't need to do anything since it will by default take all the space. And for height you can consider padding on the body and use 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>

或在所有边沿上填充而没有空白:

Or padding on all the sides without margin:

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上设置宽度/高度

Or a fixed element and you don't have to bother setting width/height on body/html

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

<body>
  <div></div>
</body>

您还可以考虑使用透明边框:

You can also consider the use of transparent border:

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>

这篇关于div是否可以使用基于像素的边距填充整个视口,而不使用CSS3 calc属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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