问题:
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? 这让我疯狂了好几天了,但实际上这是我在过去几年中一直存在的问题:使用HTML / CSS我怎样才能制作出具有宽度和/或宽度的元素高度是它的父元素的100%,仍然有适当的填充或边距?
By "proper" I mean that if my parent element is 200px
tall and I specify height = 100%
with padding = 5px
I would expect that I should get a 190px
high element with border = 5px
on all sides, nicely centered in the parent element. 通过“正确”我的意思是,如果我的父元素是200px
高,我指定height = 100%
, padding = 5px
我希望我应该获得一个190px
高元素, border = 5px
的所有边,很好地居中在父元素。
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? 有谁知道完成这个(看似简单)任务的方法?
Oh, and for the record I'm not terribly interested in IE compatibility so that should (hopefully) make things a bit easier. 哦,为了记录,我对IE兼容性并不十分感兴趣,所以应该(希望)让事情变得更容易一些。
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>
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. 接下来的挑战是让黑盒子在所有边缘都显示25像素的填充,而页面不会变得足够大以至于需要滚动条。
解决方案:
参考一: https://stackoom.com/question/22Nv/CSS-高度-填充-边距参考二: https://oldbug.net/q/22Nv/CSS-100-height-with-padding-margin
来源:oschina
链接:https://my.oschina.net/u/4432649/blog/4328175