CSS div 中的 <h1> 下划线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11659290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:35:26  来源:igfitidea点击:

Underline <h1> within a div

cssborder

提问by Michiel

I'm trying to underline a h1-title, but for some reason it always takes the whole length of the parent div. The only way I was able to do so, was by adding the position: absolute-property in the css...

我试图在h1-title下划线,但由于某种原因,它总是占用父 div 的整个长度。我能够这样做的唯一方法是position: absolute在 css 中添加-property ...

This is the design:
enter image description here

这是设计:
在此处输入图片说明

And this is what I get:
enter image description here

这就是我得到的:
在此处输入图片说明

Point is to get the blue line only as wide as the h1and a gray border line under the parent div.

要点是使蓝线仅h1与父div 下的灰色边框线一样宽。

HTML:

HTML:

<div class="title">
    <h1>Contacteer ons</h1>
</div>

CSS:

CSS:

h1 {
    border-bottom: 8px solid #57c4d0;
    position: absolute; /* As I've said, adding this allowed me to do so, but the result was far from ideal! */
}

.title {
    border-bottom: 1px solid #dedede;
}

I'm planning on using the HTML across my whole website (each h1will be different in length, adding a fixed width on each title isn't an option), so I'm looking for a robust solution. Anyone with advice?

我计划在我的整个网站上使用 HTML(每个网站的h1长度都不同,在每个标题上添加固定宽度不是一种选择),所以我正在寻找一个强大的解决方案。有人有建议吗?

回答by Jon Newmuis

You can change h1to display: inline-block;

您可以更改h1display: inline-block;

See a live example at (added margin-bottomto .titlefor clarity):

请参阅(为清楚起见添加margin-bottom.title)的现场示例:

http://jsfiddle.net/P4BGC/

http://jsfiddle.net/P4BGC/

回答by Raffaele

See this fiddle. H1 is a a block element, so it grows to fill its parent. You can set display: inline, but I also suggest to put it in its own div (or any other element with display: block) so you ensure that no content goes along side.

看到这个小提琴。H1 是一个块元素,因此它会增长以填充其父元素。您可以设置display: inline,但我也建议将其放在自己的 div(或任何其他带有 的元素display: block)中,以确保没有内容同时出现。

<div><h1>Hello, world</h1></div>
Lorem ipsum

the css

css

?h1 {
  border-bottom: 3px solid red;
  display: inline;
}?

回答by KUKEN

You could also use CSS style text-decoration.

您也可以使用 CSS 样式text-decoration

html:

html:

<div><h1>Hello, world</h1></div>

css:

css:

    h1 {
        text-decoration: underline;
    }