【问题标题】:Equalize the height of left and right div, prevent right div from going below left div均衡左右div的高度,防止右div低于左div
【发布时间】:2013-08-21 15:46:26
【问题描述】:

我有一个 HTML 页面,其内容使用CSS 分为左右部分。左侧内容的高度小于右侧内容的高度。因此,右侧内容 div 也位于左侧内容 div 下方。最终右边内容的边框不是直线。

  1. 如何避免右侧内容向左蔓延?
  2. 如何使左侧内容的高度增加到右侧内容的高度(使用 javascript)?

<html>

<head>
    <title>My Page</title>
    <style type="text/css">
        .myContent {
            width: 100%;
        }

        .myHeader {
        }

        .leftPart {
            border: 1px solid blue;
            width: 200px;
            clear: left;
            float: left;
            background-color: red;
        }

        .rightPart {
            border: 1px solid orange;
            width: 100%;
            background-color: beige;
        }
    </style>
</head>

<body>

    <header>
        <div class="myHeader">
            H
        </div>
    </header>

    <div id="body">
        <div class="myContent">

            <div class="leftPart">
                A
            </div>
            <div class="rightPart">
                <div >
                    <label for="Sales_and_Marketing">Sales and Marketing</label>
                    <input id="SalesAndMarketing" name="SalesAndMarketing" type="text" value="" />
                </div>
                 <div >
                    <label for="Sales_and_Marketing">Sales and Marketing</label>
                    <input id="Text1" name="SalesAndMarketing" type="text" value="" />
                </div>
            </div>
        </div>
    </div>
</body>
</html>

【问题讨论】:

  • 我可能误解了您的问题,但是您可以尝试将float: right 用于.rightPart 并删除width 吗?这是你想要的?如果是,我会回答。

标签: html css


【解决方案1】:

fLoat 一个元素,将margin 设置为另一个。

.leftPart {
    border: 1px solid blue;
    width: 200px;
    float: left;
    background-color: red;
}

.rightPart {
    margin-left: 200px;
    border: 1px solid orange;
    background-color: beige;
}

JSBin Demo

更新 #1

如果您考虑使用 JavaScript,不妨看看 equalize.js

equalize.js 是一个 jQuery 插件,用于均衡 HTML 元素的 heightwidth

这是一个例子:

// Equalize the height of div element children
$('.myContent').equalize({children: '> div'});

这里是JSBin Demo

更新 #2

如果您正在寻找纯 CSS 解决方案,可以使用display: table-cell; CSS 声明。

但是老实说,我更喜欢使用 JavaScript 而不是 this,因为使用表 display 类型可能会改变Web 浏览器同时呈现页面(浏览器可能会将整个页面视为一个表格):

#body { display: table; width: 100%; }

.myContent { display: table-row; }

.leftPart {
  width: 200px;
  display: table-cell;
}

.rightPart {
  display: table-cell;
}

这里是JSBin Demo

【讨论】:

  • 谢谢。你知道我们如何解决问题的第二部分吗?
  • 将其包裹在div 中并设置.leftPart height:100%
【解决方案2】:

添加此样式:

.rightPart {
    margin-left: 200px;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    相关资源
    最近更新 更多