如何使div相对于父级的高度为100%?

2024-02-18

我坚持下面这样的事情。我需要将右上 div 设为 100% 高度(其背景颜色将覆盖主 div 的整个高度)。

<body>
    <div id="main" style="width: 800px; margin: auto; text-align: left; border: 1px solid #628221; padding: 2px; background-color: #fff;">
        <div id="left" style="float: left; width: 600px; background-color: #A7C864;">
            <div id="left-top">left-top</div>
            <div id="left-bottom">left-bottom</div>
        </div>
        <div id="right" style="float: right; width: 200px; background-color: #C7E48E;">
            <div id="right-top">right-top</div>
        </div>
        <div style="clear: both;"></div>
    </div>
</body>

工作示例在这里:http://marioosh.net/lay1.html http://marioosh.net/lay1.html

使用表很容易:http://marioosh.net/lay2.html http://marioosh.net/lay2.html


我可能误解了这个问题(您到基于表格的示例的链接不起作用),但听起来您正在尝试创建具有相同高度的两列。您可以使用多种技术,以下是其中三种:

  1. 你可以给每个DIV一个大的底部填充,以及一个同样大但负的底部边距。

    #main {
        overflow: hidden;
    }
    #left, #right {
        float: left;
        padding-bottom: 1000em;
        margin-bottom: -1000em;
    }
    

    这个解决方案并非没有问题。如果您尝试链接到其中一列中的元素(例如,其中一列中有一个元素id=foo你链接到mypage.html#foo)那么布局就会被破坏。使用这种技术添加底部边框也很困难。

    Natalie Downe 的完整示例:http://natbat.net/code/clientside/css/equalColumnsDemo/10.html http://natbat.net/code/clientside/css/equalColumnsDemo/10.html

  2. 您可以为其中一列指定负的右边距,并为另一列指定非常宽的左边框。

    #left, #right {
        float: left;
    }
    #left {
        background: red;
        width: 200px;
        margin-right: -200px;
    }
    #right {
        border-left: 200px solid red;
    }
    

    有关《粉碎》杂志的更多信息:http://coding.smashingmagazine.com/2010/11/08/equal-height-columns-using-borders-and-negative-margins-with-css/ http://coding.smashingmagazine.com/2010/11/08/equal-height-columns-using-borders-and-negative-margins-with-css/

  3. 你可以通过给予来伪造它#main包含两列背景的背景图像。这种技术称为“假柱”,当您需要复杂的背景或柱之间的装饰性边框时,该技术非常有用。

    有关 A List Apart 的更多信息:http://www.alistapart.com/articles/fauxcolumns/ http://www.alistapart.com/articles/fauxcolumns/

正如该问题的一位评论者指出的那样,您还可以使用表格。但是,除非您要显示表格数据TABLE不是适当的 HTML 元素。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使div相对于父级的高度为100%? 的相关文章

随机推荐