【问题标题】:Resize bottom border on a heading element to fit the text width and also be responsive调整标题元素的底部边框以适应文本宽度并响应
【发布时间】:2018-02-08 08:45:12
【问题描述】:

我想让底部边框更窄,响应更灵敏,同时保持文本居中。我怎么能做到这一点?我尝试显式使用 width 属性,但这显然不起作用。

演示:https://www.bootply.com/jEB0e4Ao61

h1 {
  border-bottom: 1px solid orange;
  padding-bottom: 5px;
  width: 400px;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container text-center features">
  <h1>Features</h1><br>
</div>

【问题讨论】:

    标签: html css twitter-bootstrap border centering


    【解决方案1】:

    你需要做两件事:

    1. 使用display:inline-block;
    2. 设置width: auto

    从块元素更改,以便边框将调整为文本的宽度:

    &lt;h1&gt; 是一个block 元素,它会自动拉伸到容器的 100% 宽度。将宽度设置为自动或百分比将应用于默认宽度,即 50% 将是容器宽度的 50%。

    使用inline-blockauto 的宽度将使标题仅与标题本身一样宽,这意味着您不需要针对不同屏幕尺寸的媒体查询。这将使边框成为标题本身的确切宽度。

    要使“下划线”的宽度大于文本宽度:

    如果您想在标题的两侧留出额外的空间,您可以使用填充来做到这一点。例如:

    padding-left:20px; padding-right:20px;
    

    将在标题的任一侧添加 20px,扩展元素宽度,这也将在两侧将底部边框扩展 20px。

    工作演示:

    h1 {
      border-bottom: 1px solid orange;
      display: inline-block;
      width: auto;
      text-align: center;
      margin: auto;
      padding: 0 20px 5px; /* this adds 20px to the sides, extending the border  */
    }
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    <div class="container text-center features">
      <h1>Features</h1><br>
    </div>
    <p>The "underline" for this heading extends 20px either side of the text by setting the left and width padding to 20px</p>

    【讨论】:

    • 这是一个糟糕的/hacky 解决方案,因为它需要在每个标题后添加一个&lt;br&gt;
    • @Inigo 实际上不,这不需要在每个标题后添加&lt;br&gt;...如果您尝试一下,您会发现根本不需要&lt;br&gt;为此,包含它的唯一原因是因为它位于 OP 的原始代码中。
    • 我应该澄清一下,它需要 &lt;br&gt; 或包装 &lt;span&gt; 或其他一些包装器,以使内联块标头表现为正常块。我认为这是一种 hack,因为必须更改 HTML 结构才能实现这一点,而不是纯 CSS 解决方案来“调整标题元素的底部边框以适应文本宽度”。
    • @Inigo 这实际上是对所提出问题的纯 CSS 解决方案,因为原始 HTML 已经将 &lt;h1&gt; 包含在单独的元素中。在这样的单独容器中拥有&lt;hx&gt; 元素并不少见……一些 CMS 生成带有容器元素内标题的 HTML,因此这不是一个不常见的问题或代码结构。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多