Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS, centered div, shrink to fit?

Tags:

css

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.

like image 285
dirtside Avatar asked Mar 27 '09 16:03

dirtside


People also ask

How do I shrink a div in CSS?

We can apply flex-shrink on any document in the same container and that div will shrink compared to other div's width, flex-shrink will shrink that div compared to other items in that container.

How do I reduce the size of a div?

A div's height depends on its inner elements, in your example, the first input is having a height of 100px, so the div will have at least 100px height, ignoring spacing, boarder, padding. Setting max-height on the div will hint the rendering engine to limit the height, but doesn't necessarily work all the time.

How do I center and fit an image in a div?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.

How do I make content fit in a div?

You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).


1 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"

like image 80
Josh Stodola Avatar answered Oct 05 '22 01:10

Josh Stodola