html - 内联元素的奇怪填充行为(底部填充被尊重,但顶部填充不被尊重)
问题描述
我虽然知道内联元素是如何工作的。一个很好的答案可以在这里找到:CSS display: inline vs inline-block。
它对内联元素的描述:
- 尊重左右边距和填充,但不尊重顶部和底部
内联元素仅支持左右填充,忽略顶部和底部的任何填充。但是做一些测试我发现了一个非常奇怪的行为。当为内联元素提供填充时,它会将其应用于元素的左侧和右侧,但也应用于底部但不应用于顶部。
这种行为有什么解释吗?
<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>
推荐阅读
- jquery - 使用 JQuery DataTables 选择后下拉菜单表调用需要额外单击
- arrays - 如何检查没有条目的数组和有条目的伴随数组?
- mysql - MySQL WHERE 参数顺序是否重要?
- c# - Mediatr 默认处理程序和特定处理程序
- reactjs - 第一个笑话测试失败 - 尝试导入反应
- bash - 使用 jq 将 json 作为数组读取
- angular - 如何在 Angular 10 中将数组转换为 Observable?
- tensorflow - 张量流警告消息
- java - 我的真实广告没有出现在我的应用程序中,只有测试广告
- c# - 倒数计时器 system.timers 问题 xamarin 表单