如何让DIV只占用其元素占用的水平空间?

时间:2016-06-09 20:47:50

标签: html css width space

理想情况下,我希望这适用于Mac Chrome和Firefox。如何设置DIV的样式,使其占据的水平空间等于其元素的宽度但不是更多?现在我有

<div id="searchContainer">
Enter Search Criteria To Lookup Results:<br>
<div id="search_form">
<form id="search-form" action="/users/lookup_races" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓">

<input type="text" name="first_name" id="first_name" placeholder="First Name">
<input type="text" name="last_name" id="last_name" placeholder="Last Name">
<input type="text" name="item" id="item" placeholder="Item" size="50">
<input alt="Search" type="image" src="/assets/magnifying-glass-0220f37269f90a370c3bb60229240f2ef2a4e15b335cd42e64563ba65e4f22e4.png" class="search_button">
</form></div>
</div>

,样式

#searchContainer
{
        padding: 10px;
        font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
        background-color: tan;
}

#search_form
{
    display:table-cell;
    padding: 0px;
}

#search_form form input
{
    vertical-align:middle;
}

这在JSFiddle中有说明 - https://jsfiddle.net/jzz6y71t/1/。请注意,DIV占用了父容器的整个水平空间,但我希望它只与元素的宽度一样长。

1 个答案:

答案 0 :(得分:0)

您可以稍微简化一下HTML,如下所示。

在父容器上,使用display: table,这将为您提供一个具有缩小到适合宽度(width: auto)的块元素。

您可以为图块使用其他标记,例如h1

#searchContainer {
  padding: 10px;
  font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
  background-color: tan;
  display: table;
}
#searchContainer h1 {
  margin: 5px 0;
  font-size: 1.0em;
}
#search_form {
  display: table-cell;
  padding: 0px;
}
#search_form form input {
  vertical-align: middle;
}
<div id="searchContainer">
  <h1>Enter Search Criteria To Lookup Results:</h1>
  <form id="search-form" action="/users/lookup_races" accept-charset="UTF-8" method="get">
    <input name="utf8" type="hidden" value="✓">
    <input type="text" name="first_name" id="first_name" placeholder="First Name">
    <input type="text" name="last_name" id="last_name" placeholder="Last Name">
    <input type="text" name="item" id="item" placeholder="Item" size="50">
    <input alt="Search" type="image" src="/assets/magnifying-glass-0220f37269f90a370c3bb60229240f2ef2a4e15b335cd42e64563ba65e4f22e4.png" class="search_button">
  </form>
</div>