双列布局中右列高度与左列不等
下面的代码是双列布局 html 和 css 代码:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title> <style> .parent { display: flex; height: 200px; border: solid darkcyan 1px; overflow-y: auto; } .left { background: lightblue; height: 300px; width: 50%; } .right { width: 50%; background-color: lightcoral; } </style> </head> <body> <div class="parent"> <div class="left"></div> <div class="right"></div> </div> </body> </html>
运行此代码后,会发现右列的高度与左列不相等。这个问题是如何解决的?
解决方案
要解决这个问题,可以将 .parent 的子元素包装在一个额外的 .box 容器中,如下所示:
<div class="parent"> <div class="box"> <div class="left"></div> <div class="right"></div> </div> </div>
通过添加 .box 容器并在其中包裹 .left 和 .right 元素,可以使这两个元素的高度受 .box 容器内容的影响。由于 .box 容器没有指定高度,因此其高度将由其包含的子元素撑开,从而确保 .left 和 .right 的高度相等。