tags:

views:

2780

answers:

4

Here's what I want:

text text text text text text text text text text text
text text text text text text text text text text text
                   +-----------+
                   | some text |
                   +-----------+
text text text text text text text text text text text
text text text text text text text text text text text

...where the "some text" block is a div. I want the div to be the minimum width necessary to contain its text without wrapping. If the text is too long to fit without wrapping, then it's okay if it wraps.

I do NOT want to set an explicit width for the div. I don't want to set min-width or max-width either; like I said, if there's too much text to contain on one line without wrapping, then it's okay if it wraps.

+2  A: 
Koistya Navin
+1 DIV is just the wrong element for this.
Aaron Digulla
Well, agreed, but you're adding unnecessary elements as well (span).
Seb
This doesn't work either ;)
Seb
It works, I can make a screenshot :)
Koistya Navin
A: 

Something like this?

<html>
<head>
</head>
<body style="text-align: center;">

   <div style="width: 500px; margin: 0 auto;">

       <p>text text text text text text text text text text text text text text text text text text text text text text</p>

       <div>hello</div>

       <p>text text text text text text text text text text text text text text text text text text text text text text</p>

   </div>


</body>

David Caunt
+4  A: 

DIV elements are block-level by default, which means they automatically get 100% width. To change that, use this CSS...

.centerBox {
  display:inline-block;
  text-align:center;
}


<div class="centerBox">
  Some text
</div>

EDIT: Updated to use a CSS class rather than inline attribute and changed "block" to "inline-block"

Josh Stodola
‘width: auto’ is redundant and can be omitted. You'd also need to set text-align-center on the parent, obviously. A technically correct approach, although possibly mutating a div to inline isn't quite what the OP wanted!
bobince
This doesn't quite work, since if you do have multiple lines of text, any formatting (borders, padding, etc.) are applied to each separate part. But inline-block DOES work! Yay!
dirtside
See author's response below.
dirtside
you can replace it with "span" element and then you won't need to specify "display: inline: width: auto"but your solution doesn't place "some text" in the center
Koistya Navin
"inline-block" doesn't work in all browsers.
Koistya Navin
+1  A: 

Props to Josh Stodola, although he wasn't exactly right. The property needed is:

display: inline-block;

Which has solved my problem. Yay!

dirtside
inline-block doesn't work in some browsers. Don't use it if you need cross-browser support.
Koistya Navin