【问题标题】:How do I make a DIV only take up horizontal space its elements take up?如何使 DIV 仅占用其元素占用的水平空间?
【发布时间】:2016-06-09 20:47:50
【问题描述】:

理想情况下,我希望它适用于 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 占据了父容器的整个水平空间,但我希望它只与元素的宽度一样长。

【问题讨论】:

  • 一般情况下,如果内容中断到第二行这是不可能的(没有JS)。这不是 line-box 模型的工作方式。
  • 如果可以解决问题,我可以使用 Javascript。我需要什么 JS?

标签: html css width space


【解决方案1】:

您可以稍微简化您的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 2013-04-08
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多