CSS 100%高度,带填充/边距 [英] CSS 100% height with padding/margin

查看:312
本文介绍了CSS 100%高度,带填充/边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已经驱使我疯了几天现在,但在现实中,这是一个问题,我已经打破了和过去几年:使用HTML / CSS如何使一个元素有一个宽度和/或高度是其父元素的100%,并且仍然具有适当的填充或边距?

This has been driving me crazy for a couple of days now, but in reality it's a problem that I've hit off and on for the last few years: With HTML/CSS how can I make an element that has a width and/or height that is 100% of it's parent element and still has proper padding or margins?

通过适当我的意思是如果我的父元素是200px高,我指定100%的高度与5px填充我希望我应该得到一个190px高元素与5px边框的所有边,很好地集中在父元素。

By "proper" I mean that if my parent element is 200px tall and I specify 100% height with 5px padding I would expect that I should get a 190px high element with 5px "border" on all sides, nicely centered in the parent element.

现在,我知道这不是标准盒子模型指定它应该工作(虽然我想知道为什么,确切...),所以明显的答案不工作:

Now, I know that that's not how the standard box model specifies it should work (although I'd like to know why, exactly...), so the obvious answer doesn't work:

#myDiv {
    width: 100%
    height: 100%;
    padding: 5px;
}

但是在我看来,必须有一种可靠的生产方式对任意大小的父级的效果。有没有人知道一个完成这个(看起来简单)任务的方法?

But it would seem to me that there must be SOME way of reliably producing this effect for a parent of arbitrary size. Does anyone know of a way of accomplishing this (seemingly simple) task?

哦,对于记录我不是非常感兴趣的IE兼容性, )使事情更容易一些。

Oh, and for the record I'm not terribly interested in IE compatibility so that should (hopefully) make things a bit easier.

EDIT:由于提出了一个示例,以下是我能想到的最简单的例子:

Since an example was asked for, here's the simplest one I can think of:

<html style="height: 100%">
    <body style="height: 100%">
        <div style="background-color: black; height: 100%; padding: 25px"></div>
    </body>
</html>

然后挑战是让黑盒子在所有边上显示一个25像素的填充

The challenge is then to get the black box to show up with a 25 pixel padding on all edges without the page growing big enough to require scrollbars.

推荐答案

我学会了如何做这些事情阅读 PRO HTML和CSS设计模式 display:block div 的默认显示值,但我想明确它。容器必须是正确的类型; position 属性固定相对 absolute

I learned how to do these sort of things reading "PRO HTML and CSS Design Patterns". The display:block is the default display value for the div, but I like to make it explicit. The container has to be the right type; position attribute is fixed, relative, or absolute.

.stretchedToMargin {
  display: block;
  position:absolute;
  height:auto;
  bottom:0;
  top:0;
  left:0;
  right:0;
  margin-top:20px;
  margin-bottom:20px;
  margin-right:80px;
  margin-left:80px;
  background-color: green;
}

<div class="stretchedToMargin">
  Hello, world
</div>

小提琴 by Nooshu的评论

Fiddle by Nooshu's comment

这篇关于CSS 100%高度,带填充/边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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