如何使用HTML/CSS实现相同的高度div(并排放置)?

Jam*_*mes 13 javascript css xhtml jquery

我在容器内有两个div.一个在左边,一个在右边,并排.即使它们具有不同的内容,我怎样才能使每个人具有相同的高度.

例如,右侧div有很多内容,并且是左侧div的高度的两倍,如何使左侧div伸展到右侧div的相同高度?

是否有一些JavaScript(jQuery)代码来实现这一目标?

ale*_*lex 17

可以使用jQuery,但有更好的方法来做到这一点.

这类问题出现了很多,一般有3个答案......

1.使用CSS

这是"最好"的方法,因为它是最语义纯粹的方法(没有诉诸JS,它有自己的问题).最好的方法是使用display: table-cell和相关的值.您也可以尝试使用虚假背景技术(可以使用CSS3渐变).

2.使用表格

这看起来效果很好,但却牺牲了非语义布局.你也会引起纯粹主义者的轰动.我几乎避免使用表格,你也应该这样做.

3.使用jQuery/JavaScript

这有利于拥有最多的语义标记,除非禁用JS,否则您将无法获得所需的效果.


小智 11

这是使用纯CSS做到这一点的方法,但是,正如您在示例中所注意到的(在IE 7和Firefox中有效),边界可能很难 - 但它们并非不可能,所以这一切都取决于您想要的做.此示例假定body> wrapper> content container>第1列和第2列的相当常见的CSS结构.

关键是底部边距及其取消填充.

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Equal Height Columns</title>
<style type="text/css">
<!--
* { padding: 0; margin: 0; }
#wrapper { margin: 10px auto; width: 600px; }
#wrapper #main_container { width: 590px; padding: 10px 0px 10px 10px; background: #CCC; overflow: hidden; border-bottom: 10px solid #CCC; }
#wrapper #main_container div { float: left; width: 263px; background: #999; padding: 10px; margin-right: 10px; border: 1px solid #000; margin-bottom: -1000px; padding-bottom: 1000px; }
#wrapper #main_container #right_column { background: #FFF; }
-->
</style>
</head>

<body>
<div id="wrapper">
    <div id="main_container">
        <div id="left_column">
            <p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
        </div><!-- LEFT COLUMN -->
        <div id="right_column">
          <p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
          <p>&nbsp;</p>
          <p>For example, the right div has a lot of content, and is double the height of the left div, how do I make the left div stretch to the same height of the right div?</p>
          <p>&nbsp;</p>
          <p>Is there some JavaScript (jQuery) code to accomplish this?</p>
        </div><!-- RIGHT COLUMN -->
    </div><!-- MAIN CONTAINER -->
</div><!-- WRAPPER -->
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

这就是它的样子:

在此输入图像描述