html - 内联元素的奇怪填充行为(考虑底部填充,但不考虑顶部填充)

标签 html css padding

我虽然知道内联元素是如何工作的。可以在这里找到解释它的一个很好的答案:CSS display: inline vs inline-block .

关于内联元素的说法:

  1. respect left & right margins and padding, but not top & bottom

内联元素仅支持左右填充,并忽略为顶部和底部指定的任何填充。但做了一些测试后我发现了一个非常奇怪的行为。当给内联元素赋予填充时,它会将其应用于元素的左侧和右侧,但也会应用于底部,但不会应用于顶部。

对于这种行为有什么解释吗?

<html>
    <head>
        <style>
            * {
                box-sizing: border-box;
                padding:0;
                margin:0;
            }
            .parent{
                display:inline;
                background-color: red;
                padding: 10rem;
                color:white;
            }
        </style>
    </head>
    <body>
        <div class="parent">Whatever</div>
    </body>
</html>

最佳答案

使用浏览器工具检查该元素,您会发现还有一个 padding-top 为 10em,这在您的代码片段中不可见。

原因:虽然内联元素有内边距,但它不会影响其上方和下方的距离 - 线条(即文本的基线)与其所在的垂直位置相同将是(或者更好:是)没有填充。这里的填充只是创建一个溢出区域,您只有在定义了背景时才能看到该区域。

请参阅我的代码片段,其中我添加了一个带有 12em padding-top 的包装器以及内联 div 前后以及包装器 div 前后的一些文本,以演示所发生的情况。

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.wrap1 {
  padding-top: 12em;
  background: green;
  /* display: block; is the default here */
}

.parent {
  display: inline;
  background-color: red;
  padding: 10rem;
  color: white;
}

.y {
  background: rgba(255, 255, 0, 0.4);
  border-radius: 50%;
  padding: 0.6em 0.15em 0.6em 0.1em;
}
<body>
  <div>This is in a separate div which preceds the inline div and its wrapper.</div>
  <div class="wrap1">
    this is on the same the line
    <div class="parent">Whatever</div> yes it is
  </div>
  <div>And this is in a separate div following the inline div and its wrapper.</div>
  <p>And here is another line with one (inline) <span class="y">word</span> that has a padding in a way that <em>might</em> be considered useful.</p>
</body>

关于html - 内联元素的奇怪填充行为(考虑底部填充,但不考虑顶部填充),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68217653/

相关文章:

javascript - 我想使用 javascript 为我的 id ="checkimg"设计一个样式

javascript - 在保留其他值的同时更改 CSS3 的翻译?

css - Twitter Bootstrap 和大于按钮中的标准图标

javascript - 如何随机化图像的顺序?

javascript - 想要在 html 页面中使用 jquery 或 javascript 显示和隐藏数据

html - 如何在纯CSS中创建颜色自定义滚动条?

javascript - 更改尺寸时 HTML 幻灯片图像大小不会增加

javascript - 在应用文档样式之前调用 window.print 触发

android - 如何向 Android 的 RecyclerView 添加一个简单的 8dp 页眉/页脚?

html - 图片无边框