user70192
user70192

Reputation: 14204

Make a <div> to shrink to fit the content

I have a div defined like the following:

<div id="overlay" style="z-index:1000; position:relative; top:-20px; left:120px; ">
  <div style="background-color:#ffffff;">
    <label for="valueInput">Value</label>
    <input type="number" value="1.5" id="valueInput" name="valueInput" />
    <label for="valueUnit">Units</label>
    <select id="valueUnit" name="valueUnit">
      <option value="cu">Cubits</option>
      <option value="o">Other</option>
    </select>
    <p>Please make your selection</p>
  </div>
</div>

Currently, this DIV fills the width of the available area. In other words, the box looks like the following:

+---------------------------------------------------------------+
| Value [        ]                                              |
| Please make your selection                                    |
+---------------------------------------------------------------+

However, I want the box to fit tight around my content so that it looks like the following:

+----------------------------+
| Value [        ]           |
| Please make your selection |
+----------------------------+

How do I do this with CSS?

Thank you!

Upvotes: 0

Views: 142

Answers (2)

Dmitriy
Dmitriy

Reputation: 4503

use display: inline-block

body{
    margin: 50px;
}

#overlay{
    display: inline-block; 
    position:relative; top:-20px; left:120px;
    z-index:1000; 
    border: 1px solid #ccc;     
}
<div id="overlay">
  <div style="background-color:#ffffff;">
    <label for="valueInput">Value</label>
    <input type="number" value="1.5" id="valueInput" name="valueInput" />
    <label for="valueUnit">Units</label>
    <select id="valueUnit" name="valueUnit">
      <option value="cu">Cubits</option>
      <option value="o">Other</option>
    </select>
    <p>Please make your selection</p>
  </div>
</div>

Upvotes: 3

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

Inline-block will make the div take up the minimum amount of width as possible:

#overlay {
  display:inline-block;
  border:1px solid black; /* You can see the width of the div */
}
<div id="overlay">
  <div>
    <label for="valueInput">Value</label>
    <input type="number" value="1.5" id="valueInput" name="valueInput" />
    <label for="valueUnit">Units</label>
    <select id="valueUnit" name="valueUnit">
      <option value="cu">Cubits</option>
      <option value="o">Other</option>
    </select>
    <p>Please make your selection</p>
  </div>
</div>

Upvotes: 1

Related Questions