【问题标题】:Weird padding behaviour for inline element (bottom padding is respected but top padding doesn't)内联元素的奇怪填充行为(底部填充被尊重,但顶部填充不被尊重)
【发布时间】:2021-09-13 23:07:18
【问题描述】:

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

关于内联元素的说法:

  1. 尊重左右边距和内边距,但不尊重顶部和底部

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

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

<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>

【问题讨论】:

    标签: html css padding


    【解决方案1】:

    使用浏览器工具检查元素,你会看到还有一个 10em 的padding-top,这在你的 sn-p 中是不可见的。

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

    查看我的 sn-p,我在其中添加了一个包含 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/CSS 创建者喝醉了。看不出这会有什么用。它似乎更多的是某种副作用。谢谢你的解释。
    • 好吧,是和否:我在我的 sn-p 中添加了一些可能需要的行为(圆形文本突出显示而不影响行距)。
    猜你喜欢
    • 2010-11-26
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2014-10-13
    相关资源
    最近更新 更多