html - 带有显示 :table extends out of parent 的边框元素

标签 html css google-chrome safari

这段代码在每个浏览器中似乎都有不同的效果。

.container {
    display: inline-block;
    border: 1px solid black;
    padding-top: 5px;
    padding-bottom: 5px;
}
.box {
    display: table;
    width: 10px;
    height: 10px;
    background-color: red;
    border: 5px solid blue;
}
<div class="container">
    <div class="box"></div>
</div>

在 Chrome 43.0 中,表格不再局限于容器:

Chrome preview

在 Safari 5.1 中,边框完全覆盖表格,因为它似乎将宽度解释为包含边框宽度:

Safari preview

在 Firefox 38.0 和 Internet Explorer 11.0 中,表格正确呈现:

Firefox and Internet Explorer Preview

理想情况是所有浏览器的行为都类似于 Firefox/Internet Explorer。

使用 box-sizing: border-box并增加 .box 的宽度包括边框宽度使所有浏览器显示 Firefox/Internet Explorer 版本,但假设边框宽度未知,有没有办法让所有主要浏览器根据 Firefox/Internet Explorer 呈现模型(不使用JavaScript)?

以下根本没有帮助:

  • 使用 table-layout: fixed.box 上.
  • 使用 border-collapse: separate.box
  • 使用 box-sizing: content-box.box
  • 使用 <table>而不是 display: table (这只是让 Chrome 的预览看起来与 Safari 的一样,我宁愿不使用表格元素。)

这个问题好像和Chrome vs. box-sizing:border-box in a display:table类似,但这个问题已经解决了。


仅供引用:

这只是展示相同问题的一个最小示例。实际问题是我有一个 <div>display: table它的宽度仅由其单元格的宽度(等于单元格的高度)和它们之间的填充定义。该 div 也恰好有边框。该 div 包含在另一个向右浮动的元素中。但是因为这个问题,当 float 容器完全靠右时,div溢出屏幕。

最佳答案

box-sizing: border-box 设置为 .box 然后给它一个大小 .box 并计算它 边框宽度

像这样:

.container {
    display: inline-block;
    border: 1px solid black;
    padding-top: 5px;
    padding-bottom: 5px;
}
.box {
    display: table;
    width: 20px;
    height: 20px;
    background-color: red;
    border: 5px solid blue;
    box-sizing:border-box;
}
<div class="container">
    <div class="box"></div>
</div>

您的行为是因为 .container 正在调整 .box 的内容和 box 的默认值 -sizingcontent-box 所以边框被忽略了。

添加了另一个解决方案,因为上述解决方案需要事先知道边框宽度

尝试将 display: table-cell 设置为 .box 中的内容

.container {
    display: inline-block;
    border: 1px solid black;
    padding-top: 5px;
    padding-bottom: 5px;
}
.box {
    display: table;
    border: 5px solid blue;
}

.cell {
    display: table-cell;
    width: 10px;
    height: 10px;
    background-color: red;
}
<div class="container">
    <div class="box">
        <div class="cell"></div>
    </div>
</div>

关于html - 带有显示 :table extends out of parent 的边框元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831399/

相关文章:

html - 取消悬停时过渡不会缓和

javascript - 在 modal/div 中显示 ajax 响应 - 当响应为网页形式时

html - 何时以及为何使用显示内联 block

jquery - 如何设置视频 iFrame 的样式?

google-chrome - CSS3 - 如何在 Chrome 的文本区域和输入中设置所选文本的样式?

javascript - jQuery如何设置点击div中的href?

javascript - 如何在单击时向按钮添加类

javascript - 如何使用 JavaScript 将图像插入到 alertify.js 警报中?

google-chrome - 为什么我在 chrome 开发者工具中看不到 301 重定向?

html - 粗体标签在IE和chrome中的不同效果