Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

Tags:

html

css

I am stuck on figuring out some css, I need a section of my form to look like the following,

CSS float left

I have tried every variation I can think of,

I have given the labels a fixed width and floated them left, then given the inputs the same width and floated them left.

I am all out of ideas, how can I achieve this please?

like image 840
sea_1987 Avatar asked Feb 05 '11 14:02

sea_1987


People also ask

How do I align two input fields side by side in HTML?

try setting specific width to your text-boxes with display: inline-block property. Glad it worked. Then can you please accept my answer. Hello again, it works fine on desktop but on mobile it'a aligned weirdly when placed in the footer.

How do I show a form side by side?

1. Wrap your forms in a <div> and apply float: left; to the wrapper: <div style="float:left;"> <form> input,submit etc </form> </div> 2. Use display:inline-block on your wrapper <div style="width:50%; margin:auto;"> <div style="display:inline-block; width:45%;text-align:center;"> <form> input, submit ...

How do I display form elements side by side in HTML?

1. Display: Inline-Block. The first way you can use is the display: inline-block method. This method is a simple and classic CSS technique for positioning elements side by side.


2 Answers

You need an HTML element for each column in your layout.

I’d suggest:

HTML

<div class="two-col">
    <div class="col1">
        <label for="field1">Field One:</label>
        <input id="field1" name="field1" type="text">
    </div>

    <div class="col2">
        <label for="field2">Field Two:</label>
        <input id="field2" name="field2" type="text">
    </div>
</div>

CSS

.two-col {
    overflow: hidden;/* Makes this div contain its floats */
}

.two-col .col1,
.two-col .col2 {
    width: 49%;
}

.two-col .col1 {
    float: left;
}

.two-col .col2 {
    float: right;
}

.two-col label {
    display: block;
}
like image 146
Paul D. Waite Avatar answered Sep 22 '22 07:09

Paul D. Waite


<form>
  <label for="company">
    <span>Company Name</span>
    <input type="text" id="company" />
  </label>
  <label for="contact">
    <span>Contact Name</span>
    <input type="text" id="contact" />
  </label>
</form>

label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }

Illustrated at http://jsfiddle.net/H3y8j/

like image 21
Scott Brown Avatar answered Sep 23 '22 07:09

Scott Brown