Html 有边框环绕文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4689481/
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-29 06:09:22  来源:igfitidea点击:

Have border wrap around text

htmlcsslayout

提问by Steven Lu

Suppose I have a div with some text in it

假设我有一个带有一些文本的 div

<div id='page' style='width: 600px'>
  <h1 style='border:2px black solid; font-size:42px;'>Title</h1>
</div>

The border for the heading will extend all 600 pixels across the page, but I want the word "Title" to fit tightly inside. However, I don't know ahead of time how many pixels wide the word is so I can't for example put the "Title" inside a div and set its width explicitly.

标题的边框将在整个页面上扩展所有 600 像素,但我希望“标题”这个词紧贴在里面。但是,我不知道这个词有多少像素宽,所以我不能例如将“标题”放在 div 中并明确设置其宽度。

Is there an easy way to make a border fit around text that does not fully extend horizontally across an area?

是否有一种简单的方法可以使边框适合不完全水平延伸到整个区域的文本?

回答by Jonathon Bolster

This is because h1is a block element, so it will extend across the line (or the width you give).

这是因为h1是一个块元素,所以它会跨过这条线(或你给定的宽度)。

You can make the border go only around the text by setting display:inlineon the h1

您可以通过设置display:inlineh1使边框仅围绕文本

Example: http://jsfiddle.net/jonathon/XGRwy/1/

示例:http: //jsfiddle.net/jonathon/XGRwy/1/

回答by shlgug

Try putting it in a span element:

尝试将其放在 span 元素中:

<div id='page' style='width: 600px'>
  <h1><span style='border:2px black solid; font-size:42px;'>Title</span></h1>
</div>

回答by Fidi

Not sure, if that's what you want, but you could make the inner div an inline-element. This way the border should be wrapped only around the text. Even better than that is to use an inline-element for your title.

不确定,如果这是您想要的,但您可以将内部 div 设为内联元素。这样边框应该只包裹在文本周围。比这更好的是为您的标题使用内联元素。

Solution 1

解决方案1

<div id="page" style="width: 600px;">
    <div id="title" style="display: inline; border...">Title</div>
</div>

Solution 2

解决方案2

<div id="page" style="width: 600px;">
    <span id="title" style="border...">Title</span>
</div>

Edit: Strange, SO doesn't interpret my code-examples correctly as block, so I had to use inline-code-method.

编辑:奇怪,所以没有将我的代码示例正确解释为块,所以我不得不使用内联代码方法。

回答by Ming Huang

Try this and see if you get what you are aiming for:

试试这个,看看你是否达到了你的目标:

<div id='page' style='width: 600px'>
  <h1 style='border:2px black solid; font-size:42px; width:fit-content; width:-webkit-fit-content; width:-moz-fit-content;'>Title</h1>
</div>