CSS, centered div, shrink to fit?

Viewed 89010

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.

10 Answers

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"

<style type="text/css">
    /* online this CSS property is needed */
    p.block {
        text-align: center;
    }
    /* this is optional */
    p.block cite {
        border: solid 1px Red;
        padding: 5px;
    }    
</style>

<p>Some text above</p>
<p class="block"><cite>some text</cite></p>
<p>Some text below</p>

Hint: don't use DIVs for text blocks (for SEO and a better semantic purposes)

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

display: inline-block;

Which has solved my problem. Yay!

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>

display: inline-block won't work if the block is not closed just before and just after the desired centered text. What you really need is to set width: fit-content; margin: auto; on block element, see the snippet.

.center {
  display: block;
  width: fit-content;
  margin: 1em auto;
  padding: .5em;
  text-align: right;
  background: yellow;
}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce fringilla diam sagittis, scelerisque ipsum ac, imperdiet tortor. Curabitur dapibus metus eu neque consectetur hendrerit. Cras interdum faucibus malesuada.

<div class="center">
  Lorem ipsum yourself, buddy!<br>
  Try to align this!
</div>

In auctor aliquam erat in pharetra. Suspendisse potenti. Pellentesque vehicula interdum sem vel tristique. Nullam erat nisl, imperdiet et turpis ut, ornare vulputate erat.

Related