【问题标题】:Why element with 100% width and displayed as table have right margin not work?为什么具有 100% 宽度并显示为表格的元素有右边距不起作用?
【发布时间】:2017-05-17 18:57:59
【问题描述】:

在下面的代码中,当行 div 显示为 table 并且 width 设置为 100% 时,框缩小并且似乎 margin-right 设置为 nil 或者您可以说它没有显示任何影响。

但是,当我删除 width:100%,margin-right` 时会被应用

* {
  box-sizing: border-box;
}
.container {
  padding-left: 15px;
  padding-right: 15px;
}
.row {
  background-color: #cdecde;
  margin-right: -15px;
  margin-left: -15px;
}
.table {
  display: table;
  width: 100%;
}
.col {
  padding: 20px 15px;
}
<div class="container">
  <div class="row table">
    <div class="col">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae autem minima minus eligendi, enim dicta quibusdam reiciendis veniam maiores accusamus ut, dolorum repellat, ea, odit quisquam magni dolor aliquid vero!</div>
  </div>
</div>

https://jsfiddle.net/sp30xr76/

请解释上述行为。

【问题讨论】:

    标签: html css width margin css-tables


    【解决方案1】:

    您将 negative margins 应用到 row 元素 - 这导致了 问题

    当应用 负边距 时,table 会向左移动,占用 paddingcontainer 的空间 - 尝试移除 负边距 来自row,看看它是如何水平对齐的:

    * {
      box-sizing: border-box;
    }
    .container {
      padding-left: 15px;
      padding-right: 15px;
    }
    .row {
      background-color: #cdecde;
      /*margin-right: -15px;
      margin-left: -15px;*/
    }
    .table {
      display: table;
      width: 100%;
    }
    .col {
      padding: 20px 15px;
    }
    <div class="container">
      <div class="row table">
        <div class="col">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae autem minima minus eligendi, enim dicta quibusdam reiciendis veniam maiores accusamus ut, dolorum repellat, ea, odit quisquam magni dolor aliquid vero!</div>
      </div>
    </div>

    当您不提供width: 100% 时,table 会占用完整的可用宽度,因为table 的内容是一个跨越多行的文本。

    看看当文本较少时会发生什么:

    * {
      box-sizing: border-box;
    }
    .container {
      padding-left: 15px;
      padding-right: 15px;
    }
    .row {
      background-color: #cdecde;
      margin-right: -15px;
      margin-left: -15px;
    }
    .table {
      display: table;
    }
    .col {
      padding: 20px 15px;
    }
    <div class="container">
      <div class="row table">
        <div class="col">Lorem ipsum dolor</div>
      </div>
    </div>

    希望能解决问题,谢谢!

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 1970-01-01
      • 2013-05-01
      • 2012-06-06
      • 2015-02-24
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多