Html 如何防止标题 (<h1>) 占用超过所需的宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2124355/
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
How to prevent headings (<h1>) from taking up more width than they need?
提问by Pieter
If I define a heading like <h1>
, its width is set to 100% by default.
如果我定义了一个像 的标题<h1>
,它的宽度默认设置为 100%。
Is there a way to make sure its width is set to the smallest value possible?
有没有办法确保其宽度设置为可能的最小值?
回答by Pekka
You can give it display: inline
. This will make it behave like any text element - the default for <h1>
is display: block
.
你可以给display: inline
。这将使其行为像任何文本元素-默认为<h1>
是display: block
。
There are other ways: float: left
for example, but I find this the simplest and the one with the fewest side effects.
还有其他方法:float: left
例如,但我发现这是最简单且副作用最少的方法。
Note that you will then probably have to add a <br>
to ensure a line break after the <h1>
.
请注意,您可能需要<br>
在<h1>
.
回答by DaveS
Instead of display: inline
, give it display: inline-block
. This will retain the block-like qualities of the h1 tag, except for the 100% width.
而不是display: inline
,给它display: inline-block
。这将保留 h1 标签的块状质量,除了 100% 宽度。
回答by troelskn
It's a block level element, so it follows the rules of display:block
. You can set display:inline
, which may do what you need or not, depending on the context.
它是一个块级元素,所以它遵循display:block
. 您可以设置display:inline
,这可能会满足您的需要或不需要,具体取决于上下文。
回答by Alisson Nunes
Is there a way to make sure its widthis set to the smallest value possible?
有没有办法确保其宽度设置为可能的最小值?
I think that width: fit-content;
is better.
我认为这样width: fit-content;
更好。