为什么 div display: table-row 会忽略边距?

cssweb developmentfront end technology更新于 2024/10/31 3:56:17

您可能遇到过这样的情况:多个 div 元素并排放置,并且属性设置为 display: table-cell,但它们之间没有边距。如果您想在它们之间设置边距,则需要通过外部添加边距来添加边距。

在本文中,我们将了解为什么 display: table-row 会忽略边距,以及如何添加边距(如果需要)。

如何为表格添加边距?

您可能想知道,如果我们在 table-row 外部添加边距,那么这可能会为表格添加边距。但是,让我们看看当我们外部添加边距时会发生什么。

示例

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Example of adding the margin to the table</title>
   <style>
      .dog{
         display: table-cell;
         margin: 50px;
         background-color:green;
      }
      .frog{
         display: table-cell;
         margin: 50px;
         background-color:blueviolet;
      }
   </style>
</head>
<body>
   <div class="dog">100</div>
   <div class="frog">200</div>
</body>
</html>

在上面的代码中,我们创建了两个 div 容器,并在其中添加了两个数字,并为其添加了类名。之后,在 CSS 部分,我们将这两个容器的显示方式更改为 table-row,并在外部添加了外边距。让我们看看输出结果,看看外边距是否已添加。

在上面的输出中,您可以看到这两个容器之间都没有添加外边距,请记住,我们已经将它们的显示方式更改为 table-row。

现在,您可能想知道为什么会发生这种情况。外边距应该添加到 table-row 中,为什么这里忽略了外边距?

我们在此处使用的 margin 属性应用于除表格显示类型元素之外的所有元素,这意味着 margin 属性不适用于 table-cell 属性。padding 属性也不会在表格单元格之间创建空格。那么,我们该怎么做呢?

我们可以通过 border-spacing 属性和以不同方式使用 margin 属性来为这些表格单元格添加边距。

使用 border-spacing 属性

我们要看的第一个方法是 border-spacing 属性,它将应用于父元素,并将显示设置为"表格布局",并设置 border-collapse。

以下是它的代码。

示例

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Example of adding the margin to the table</title>
   <style>
      .table {
         display: table;
         border-collapse: separate;
         border-spacing: 15px;
      }
      .row {
         display: table-row;
      }
      .cell {
         display: table-cell;
         padding: 5px;
         border: 1px solid black;
      }
   </style>
</head>
<body>
   <div class="table">
      <div class="row">
         <div class="cell">Hi everyone</div>
         <div class="cell">Welcomme to another tutorial</div>
         <div class="cell">We will learn about bhow to add margin</div>
      </div>
   </div>
</body>
</html>

在上面的代码中,我们首先创建了 div 元素,然后为其指定类名,并在 CSS 部分添加了 border-collapse 属性,并将 display 设置为 table-cell。让我们看看使用上述代码后的输出效果。

在上面的输出中,您可以看到,在使用 border-spacing 属性后,表格单元格之间添加了外边距。

使用 margin 属性

我们将使用的第二种方法是将 margin 属性添加到内部 DIV。当我们将 margin 属性添加到外部 div 时,margin 属性不起作用。margin 属性适用于内部 DIV,因此让我们看另一个示例,以便了解 margin 属性的工作原理。

示例

在下面的示例中,我们创建了两个 div,并在它们之间添加了嵌套的 div。在外部 div 中,我们使用属性 display 并将其值设置为表格单元格,并赋予这些 div 两种不同的颜色来表示它们。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Using the margin property on the inner DIVs</title>
</head>
<body>
   <div style="display: table-cell;">
      <div style="margin: 15px; background-color: lightgreen;">
         Hi everyone welcome to another tutorial!!
      </div>
   </div>
   <div style="display: table-cell; ">
      <div style="margin: 25px; background-color: lightblue;">
         Good Morning!!
      </div>
   </div>
</body>
</html>

在上面的输出中,您可以看到绿色部分和蓝色部分由边距分隔,这意味着在内部 div 中声明的边距会在表格单元格之间添加边距。

结论

margin 属性会在元素之间添加边距,但它不适用于以表格类型显示的元素。边距对于对齐网页上的元素非常重要。元素的对齐可确保用户获得适当的可读性和清晰度,并使网站看起来更简洁。


相关文章


有用资源