【问题标题】:CSS box-sizing: border-box still adding border size to element widthCSS box-sizing:border-box 仍然为元素宽度添加边框大小
【发布时间】:2020-07-02 17:28:46
【问题描述】:

下面的例子是为了演示我遇到的问题。

如果我有一个 200px 宽的容器

我在容器中添加了一个 200px 宽的行(将添加很多行)

我想将 div 添加到总共 200px 的行(每行不同)

在我将 1px 实心边框添加到 .cont div 之前,一切正常。

为什么 box-sizing 不考虑 .cont 边框?

[编辑] 三个 .cell div 不显示添加边框,没有边框所有三个 .cell div 显示。 [/编辑]

*,
*:before,
*:after {
  -webkit-box-sizing: border-box !important;
  -moz-box-sizing: border-box !important;
  -ms-box-sizing: border-box !important;
  box-sizing: border-box !important;
}

.cont {
  position: absolute;
  background-color: white;
  font-size: 12px;
  overflow: hidden;
  border: solid;
  /* Remove this and it works */
  border-color: purple;
  border-width: 1px;
  height: 200px;
  width: 200px;
  margin: 0;
  padding: 0;
}

.h_row {
  display: block;
  width: 100%;
  height: 22px;
  line-height: 22px;
  background-color: red;
  overflow: hidden;
  border-bottom: solid;
  border-bottom-color: orange;
  border-width: 1px;
  margin: 0;
  padding: 0;
}

.cell {
  display: block;
  float: left;
  font-size: 11px;
  height: 20px;
  line-height: 20px;
  text-align: left;
  text-indent: 2px;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.h_row>.cell {
  font-size: 12px;
  text-align: center;
  height: 22px;
  line-height: 22px;
  border-right: solid;
  border-right-color: pink;
  border-right-width: 1px;
  background-color: green;
}

.h_row>.cell:last-child {
  border-right: none;
}

.w50 {
  width: 50px;
}

.w100 {
  width: 100px;
}
<div class="cont">
  <div class="h_row">
    <div class="cell w100">100</div>
    <div class="cell w50">50</div>
    <div class="cell w50">50</div>
  </div>
</div>

【问题讨论】:

  • 如果我从你的 css & html 运行 sn-p,我会得到一个 200px 的宽度,包括边框。我想念什么?
  • 这正是考虑边界,你想要的是不使用内容框考虑边界
  • 对于我的测试,我使用了一个标尺插件(适用于 FF 74.0)和.cont{ transform:scale(3); transform-origin:0 0 ;},它给了我 600px。 600px/3=200px .
  • @G-Cyrillus 下面还有第三项,红框是h_row的背景,里面有height: 22px;overflow: hidden;所以你看不到第三个框
  • 这里的方法是:.w50 { width: 25%; } .w100 { width: 50%; } 所以它适合留给孩子们的 198px ...... box-sizing 没什么问题

标签: html css


【解决方案1】:

也许你可以使用盒子阴影而不是使用边框,但把它放在你的盒子里,这意味着一个 1px 的边框基本上在容器内

也许解决这个问题的另一种方法是没有像素大小,您可以尝试使用百分比来表示宽度,例如 50% 或 10%

如果你想要代码,你可以试试这个网站: link

【讨论】:

    【解决方案2】:

    你应该使用box-sizing: content-box;从元素宽度中排除边框宽度并且容器保持200px。

    【讨论】:

      【解决方案3】:

      这其实很简单。

      我错过了 .cont div 是 200 像素,左右边框为 1 像素。

      因此,它里面的 .h_row 是 198px,使用的是 box-sizing。

      因此 .cell 需要添加到 198px 而不是 200px。

      我知道这很简单——只需要一点帮助就可以找到它!

      -谢谢@ZohirSalak!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-07
        • 1970-01-01
        • 2015-06-18
        • 2021-12-13
        • 2012-07-21
        相关资源
        最近更新 更多