Resize bottom border on a heading element to fit the text width and also be responsive

我是研究僧i 提交于 2021-01-27 16:11:08

问题


I want to make the bottom border narrower and responsive while keeping text centered at the same time. How could I achieve that? I tried using width property explicitly but that is apparently not working.

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

回答1:


You need to do 2 things:

  1. use display:inline-block;
  2. set width: auto

Change from a block element so the border will resize to the width of the text:

<h1> is a block element, which will automatically stretch to 100% width of the container. setting width to auto or a percentage will apply to the default width, i.e. 50% will be 50% of the container width.

Using inline-block and width of auto will make the heading only as wide as the heading itself, which means you won't need media queries for different screen sizes. This will make the border the exact width of the heading itself.

To make the "underline" extend wider than the text width:

If you would like extra space at the sides of the heading, you can use padding to do this. For example:

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

will add 20px to either side of the heading, extending the element width which will also extend the bottom border by 20px on both sides.

Working demo:

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>


来源:https://stackoverflow.com/questions/45963746/resize-bottom-border-on-a-heading-element-to-fit-the-text-width-and-also-be-resp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!