为什么表单元素占据宽度的100%?

时间:2016-11-04 16:18:08

标签: html css twitter-bootstrap

我有一个表单元素,我想占用与其子元素相同的宽度,没有边距,但无论我做什么,浏览器使其宽度+边距占据宽度的100%。

这是html:

<div class="container">

  <form method="GET" action="http://localhost/search" accept-charset="UTF-8">
    <div class="search centered">
      <div class="input-container">
        <input type="text" name="query" class="searchbar" placeholder="What do you want to search?" />
        <button type="submit" class="search-button">Search</button>
      </div>
    </div>

  </form>

</div>

和css:

    @import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

body {
    margin: 10px;
}

.search * {
  height: 35px;

}

.searchbar {
  width: 450px;
}
.brandname {
  position: relative;
  font-size: 500%;
  font-family: 'Lato', sans-serif;
  color: #1f0e3e;
  text-align: center;
  margin-bottom: 30px;
  margin-top: 5%;
}
body {
    margin: 10px;
}

.input-container{
    float: left;
    display: block;
    outline-style: solid;
    outline-color: #e3e3e3;
    outline-width: 1px;
  }

  .searchbar{
    margin-left: 5px;
  }

  .search button {
    background-color: rgba(152,111,165,0.38);
    background-repeat:no-repeat;
    border: none;
    cursor:pointer;
    /*overflow: hidden;*/
    outline-width: 1px;
    outline-style: solid;
    outline-color: #e3e3e3;
    color: white;
}

.search input{
  outline-width: 0px;
}

form{
  height: 30px;
  width: 100px;
  margin-left: 0px;
}

here是一个小提琴,你可以看到,即使你强制表格的宽度很小,浏览器也会强制左边距占据剩下的空间。

如何摆脱这个边距并让表格自动占用其子女的空间?

1 个答案:

答案 0 :(得分:3)

将显示表添加到form元素将使其自动调整为其子元素。

form {
     display:table;
    }

这是一个工作小提琴:https://jsfiddle.net/bnah6jLe/

为什么表单默认为100%宽度

默认情况下,大多数浏览器的表单都将其显示类型设置为block。在block上下文的规范中,定义如下。

  

在块格式化上下文中,每个框的左外边缘都接触到   包含块的左边缘(从右到左格式化,右边   边缘触摸)

参考:https://www.w3.org/TR/CSS21/visuren.html#block-formatting

简而言之,除非另有说明,否则display:block的宽度为100%。

旁注

问题:为什么table用于此示例而不是inline-block

答案:我使用table代替inline-block,因为blocktable等显示上下文用作包含元素而不是组。像inline-blockinline-table这样的显示上下文用于要组合在一起的子元素。这是一个小的差异,但我认为考虑形式通常意味着容器表更合适。

相关问题