~Onlooker 2009-01-27 23:28 采纳率: 0%
浏览 375
已采纳

具有 padding / margin 的 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?

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.

转载于:https://stackoverflow.com/questions/485827/css-100-height-with-padding-margin

  • 写回答

13条回答 默认 最新

  • 叼花硬汉 2009-01-27 23:53
    关注

    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>

    Fiddle by Nooshu's comment

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集