Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have border wrap around text

Tags:

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?

like image 484
Steven Lu Avatar asked Jan 14 '11 09:01

Steven Lu


People also ask

How do I wrap text around a border in CSS?

To add a border using the style attribute, add the border CSS inside the quotes after style=. In the example below, we surrounded a paragraph (<p></p>) with a solid red border that is 3 pixels wide. First example with text surrounded by a red border.

How do you force text wrap in CSS?

Today I'm going to talk about a rarely used but extremely useful CSS property, the word-wrap. You can force long (unbroken) text to wrap in a new line by specifying break-word with the word-wrap property.


2 Answers

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/

like image 197
Jonathon Bolster Avatar answered Sep 19 '22 04:09

Jonathon Bolster


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>
like image 42
shlgug Avatar answered Sep 18 '22 04:09

shlgug