CSS 使用 display: table 让两个 div 等高

在本文中,我们将介绍如何使用 CSS 的 display: table 属性来实现让两个 div 等高的效果。在网页布局中,经常会遇到需要让多个元素等高的需求,特别是在响应式设计中。使用 display: table 属性可以方便地实现这一效果。

阅读更多:CSS 教程

display: table 属性简介

display: table 属性是 CSS 中的一个布局属性,它将元素显示为一个表格,类似于 HTML 中的 table 元素。使用 display: table 属性可以创建一个表格布局,其中包含了行和列。这样就可以通过定义表格行的属性来实现将多个元素等高。

实现两个 div 等高的方法

使用 display: table 属性可以轻松地让两个 div 元素等高。下面是一种实现的方法:

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        display: table;
        width: 100%;
    }
    .col {
        display: table-cell;
        width: 50%;
        vertical-align: top;
        border: 1px solid black;
    }
</style>
</head>
<body>

<div class="container">
  <div class="col">
    <h2>Column 1</h2>
    <p>Some text..</p>
  </div>
  <div class="col">
    <h2>Column 2</h2>
    <p>Some text..</p>
    <p>Some more text..</p>
  </div>
</div>

</body>
</html>

在上面的代码中,我们创建了一个容器类 .container,将其属性设为 display: table,宽度设为 100%。然后在容器内创建两个 div 元素,分别为 .col 类。将 .col 的属性设为 display: table-cell,并设置宽度为 50%。通过这样的设置,两个 div 元素会自适应容器的高度,即实现了等高效果。

同时,我们还可以看到两个 div 元素上设置了 vertical-align: top 属性,用于将内容垂直居中。另外,为了更清晰地显示等高效果,我们还给 border 属性加上了边框样式。

进一步应用

使用 display: table 属性并不仅限于两个 div 元素,也可以用于多个元素的等高布局。例如,我们可以将三个 div 元素并排,让它们自动适应相同的高度。

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        display: table;
        width: 100%;
    }
    .col {
        display: table-cell;
        width: 33.33%;
        vertical-align: top;
        border: 1px solid black;
    }
</style>
</head>
<body>

<div class="container">
  <div class="col">
    <h2>Column 1</h2>
    <p>Some text..</p>
  </div>
  <div class="col">
    <h2>Column 2</h2>
    <p>Some text..</p>
    <p>Some more text..</p>
  </div>
  <div class="col">
    <h2>Column 3</h2>
    <p>Some text..</p>
    <p>Some more text..</p>
    <p>Even more text..</p>
  </div>
</div>

</body>
</html>

在上面的代码中,我们将 .col 的宽度设置为 33.33%,这样就能够让三个元素等分宽度。通过 display: table 属性,我们可以轻松实现这样的等高布局。

总结

使用 display: table 属性可以方便地实现多个元素等高的效果。无论是两个 div 元素还是多个元素并排,都可以通过设置 display: table 和 display: table-cell,加上合适的宽度和垂直对齐属性,达到等高布局的目的。

可以看到,CSS 提供了丰富的布局属性,方便我们实现各种各样的页面效果。掌握这些属性的用法,可以更好地进行网页布局,提升用户体验。希望本文对您有所帮助!

最后修改:2024 年 05 月 17 日
如果觉得我的文章对你有用,请随意赞赏