【问题标题】:CSS: set div height to height of the container, but leave 10px spaceCSS:将 div 高度设置为容器的高度,但保留 10px 空间
【发布时间】:2012-05-07 12:10:12
【问题描述】:

我在父容器中有一个 div,希望它的宽度为 300 像素,高度与父容器相同,但每边的边距为 10。我找到了一些答案,可以通过将 height: 100%; margin: 10px;margin-bottom 设置为负值,例如 -20px (以补偿顶部和底部的 10px 空间)。我试过这样:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;width:100%;margin:0;padding:0;">
    <head></head>
    <body style="height:100%;width:100%;margin:0;padding:0;">
        <div style="height:100%;width:100%;margin:0;padding:0;">
            <div style="border:1px solid black;height:100%;width:300px;margin-top:10px;margin-left:10px;margin-bottom:-20px;">
                Hello world!
            </div>
        </div>
    </body>
</html>

但它不起作用。 div 与父容器高度相同,所以在底部重叠...

【问题讨论】:

    标签: html css


    【解决方案1】:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;width:100%;margin:0;padding:0;">
        <head></head>
        <body style="height:100%;width:100%;margin:0;padding:0;">
            <div style="height:100%;width:100%;margin:0;padding:0;position:relative">
                <div style="border:1px solid black;width:300px;position:absolute;left:10px;top:10px;bottom:10px;">
                    Hello world!
                </div>
            </div>
        </body>
    </html>
    

    也由 JAVASCRIPT 提供

    <div style="height:100%">
        <div class="child"></div>    
    </div>
    

    JS

    docHeight = document.body.clientHeight;
    childHeight = docHeight-22; //2px due to borders
    document.getElementsByClassName('child').style.height = childHeight;
    

    CSS

    .child {padding:10px}

    【讨论】:

    • 我不得不删除内部 div 中的 height:100%;,现在您的解决方案有效,谢谢!
    • 如果你愿意,我还添加了 JS 解决方案
    【解决方案2】:
    <html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;width:100%;margin:0;padding:0;">
    <head></head>
    <body style="height:100%;width:100%;margin:0;padding:0;">
        <div style="height:100%;width:100%;margin:0;padding:10; background-color:#FF0000;">
            <div style="border:1px solid black;height:100%;width:300px; background:#0000FF;">
                Hello world!
            </div>
        </div>
    </body>
    

    只需去除背景颜色。

    我向父级添加填充并删除子级的边距

    【讨论】:

    • 我刚刚尝试了您的代码,但它不起作用。现在内部 div 没有空间到容器了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2012-01-18
    • 2015-02-26
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多