问题描述
使用 HTML/CSS,如何制作宽度和/或高度为其父元素 100% 且仍然具有适当填充或边距的元素?
正确"的意思是,如果我的父元素是 200px
高并且我指定 height = 100%
和 padding = 5px
我我希望我应该得到一个 190px
高的元素,所有边都有 border = 5px
,很好地居中在父元素中.
现在,我知道这不是标准盒模型指定它应该工作的方式(尽管我想知道为什么,确切地说......),所以明显的答案不起作用:
#myDiv {宽度:100%高度:100%;填充:5px;}
但在我看来,必须有某种方法可以为任意大小的父级可靠地产生这种效果.有谁知道完成这个(看似简单的)任务的方法吗?
哦,为了记录,我对 IE 兼容性不是很感兴趣,所以(希望)应该让事情变得更容易一些.
既然要求了一个例子,这是我能想到的最简单的一个:
接下来的挑战是让黑框在所有边缘上显示 25 像素的填充,而页面不会变得大到需要滚动条.
我通过阅读PRO HTML 学会了如何做这些事情和 CSS 设计模式".display:block
是 div
的默认显示值,但我喜欢使其明确.容器必须是正确的类型;position
属性为 fixed
、relative
或 absolute
.
.stretchedToMargin {显示:块;位置:绝对;高度:自动;底部:0;顶部:0;左:0;右:0;边距顶部:20px;底边距:20px;边距右:80px;左边距:80px;背景颜色:绿色;}
你好,世界
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?
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.
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.
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.
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>
这篇关于CSS 100% 高度,带填充/边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!