Leo
Leo

Reputation: 4438

How do I make the input text field take all available width?

I am trying to stretch an input text field to the available width (minus margins). This does not work. Why?

  <div style="background:yellow; padding:5px;">
    <input id="test-input" type="text" />
  </div>
  <style type="text/css">
    * { box-sizing: border-box; }
    #test-input {
        margin-left: 10px;
        margin-right: 10px;
        width: auto;
        display: block;
        border: 1px black solid;
    }
  </style>

Upvotes: 1

Views: 424

Answers (1)

Hashem Qolami
Hashem Qolami

Reputation: 99554

You could use CSS3 calc() function to calculate the width excluding the left/right margins, as follows:

#test-input {
    margin-left: 10px;
    margin-right: 10px;
    width: calc(100% - 20px); /* Exclude left/right margins */
    display: block;
}

WORKING DEMO

Or use padding for the container instead of using margin for the input:

<div class="parent">
    <input id="test-input" type="text" />
</div>
.parent {
    padding: 5px 15px;
}

#test-input {
    width: 100%;
    display: block;
}

WORKING DEMO

Upvotes: 3

Related Questions