使<div>缩小以适合内容

时间:2015-06-11 13:33:50

标签: html css

我的div定义如下:

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

目前,此DIV填充可用区域的宽度。换句话说,该框如下所示:

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

但是,我希望该框能够紧贴我的内容,以便它看起来如下所示:

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

如何使用CSS执行此操作?

谢谢!

2 个答案:

答案 0 :(得分:3)

使用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>

答案 1 :(得分:1)

内联块会使div占用最小宽度:

&#13;
&#13;
#overlay {
  display:inline-block;
  border:1px solid black; /* You can see the width of the div */
}
&#13;
<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>
&#13;
&#13;
&#13;