user3494047 user3494047 - 1 month ago 7
CSS Question

Why does the form element take up 100% of the width?

I have a form element which I want to take up the same width as its children, with no margin, but no matter what I do the browser makes its width + margin take up 100% of the width.

Here is the 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>


and the 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;
}


and here is a fiddle where you can see that even if you force the form to have a small width, the browser forces a left-margin to take up the rest of the space.

How can i get rid of this margin and make the form automatically take up the space of its child?

Answer

Adding display table to the form element will make it auto size to it's children elements.

form {
     display:table;
    }

Here is a working fiddle: https://jsfiddle.net/bnah6jLe/

Why the form is 100% width by default

By default forms in most browsers have their display type set to block. In the specification for block context it is defined as follows.

In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch)

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

In short display:block is 100% width unless specified otherwise.