Steven Lu
Steven Lu

Reputation: 43427

Have border wrap around text

Suppose I have a div with some text in it

<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.

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

Upvotes: 30

Views: 202768

Answers (5)

CODER123
CODER123

Reputation: 51

The easiest way to do it is to make the display an inline block

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

if you do this it should work

Upvotes: 5

Ming Huang
Ming Huang

Reputation: 1370

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>

Upvotes: 10

shlgug
shlgug

Reputation: 1356

Try putting it in a span element:

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

Upvotes: 16

Fidi
Fidi

Reputation: 5834

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.

Solution 1

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

Solution 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.

Upvotes: 3

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

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

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

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

Upvotes: 47

Related Questions