Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

css - Select inputs and text inputs in HTML - Best way to make equal width?

I've got a simple form like so (illustrative purposes only)...

<form>

   <div class="input-row">
      <label>Name</label>
      <input type="text" name="name" />
   </div>

   <div class="input-row">
      <label>Country</label>
      <select name="country">
         <option>Australia</option>
         <option>USA</option>
      </select>
   </div>

</form>

My layout method using CSS is as follows...

form  {
    width: 500px;
}

form .input-row {
    display: block;
    width: 100%;
    height: auto;
    clear: both; 
    overflow: hidden; /* stretch to contain floated children */
    margin-bottom: 10px;
}

form .input-row label {
    display: block;
    float: left;
}

form .input-row input,
form .input-row select {
    display: block;
    width: 50%;
    float: right;
    padding: 2px;
}

This all aligns quite nicely, except my select element (in Firefox anyway) isn't always the same width as my other input elements. It generally is narrower by a few pixels.

I've tried changing the width to a pixel size (e.g. 200px) but it has not made a difference.

What is the best way to get these to all have the same width? I hope it doesn't resort to me setting the select's width individually, or putting them into tables...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution is to specify box model for form elements, and browsers tend to agree most when you use border-box:

input, select, textarea {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

There's normalize.css project that aggregates such tricks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...