Reputation: 4631
I've been exposed to the commandment of 'no tables for layouts' for years now, but I'm wondering if CSS still has no easy (readable) way of doing grid layouts?
It's been ages since I last did web development, and coming back to it from WPF, CSS still seems like a very limited way of coding layouts.
What I'm trying to achieve is show in the
(source: chucara.dk)
Basically, I want my form to contain 5 columns:
Next, I want to be able to place my inputs in this 'grid' so that two element on the same line share the space. Using a WPF Grid (or HTML table, I suppose), I'd just give my elements a column span.
So far I've only been able to find examples that nicely align a single input in the second row. I have tried CSS3 calc() and various other things, but no solution gives me what I want without adding way too much extra code.
Is it possible in native HTML and CSS3 to create the layout from the image?
If not, what is the cleanest way of doing it? (tables, FreeWall, jquery, or other)
Fiddle here: link
Code Reposted from Fiddle:
<form>
<div class="panel-heading">
<h3 class="panel-title">Owner</h3>
</div>
<label for="firstName">Name</label>
<input name="firstName" type="text" class="colspan2"/>
<input name="lastName" type="text" class="colspan2"/>
<label for="street">Street</label>
<input name="street" type="text" class="colspan4"/>
<label for="zipCode">ZipCode</label>
<input name="zipCode" type="text" class="colspan1"/>
<input name="town" type="text" class="colspan3"/>
</form>
My failed attempt at solving it using CSS:
form label {
display: inline-block;
float: left;
clear: left;
width: 60px;
text-align: right;
margin-right:20px;
}
form input {
display: inline-block;
float: left;
margin-bottom:4px;
margin-right:2px;
}
.colspan1 {width: calc(50% - 100px);}
.colspan2 {width: calc(50% - 100px);}
.colspan3 {width: calc(50% - 100px);}
.colspan4 {width: calc(100% - 100px);}
I'd rather use jQuery or similar to achieve this than have to add a lot of extra s or combination of CSS classes to manage how many fields are on a line, etc.
Upvotes: 2
Views: 192
Reputation: 4516
You need to adjust the pixel values in the calc functions in CSS.
.colspan1 {
width: calc(25% - 25px);
}
.colspan2 {
width: calc(50% - 50px);
}
.colspan3 {
width: calc(75% - 75px);
}
.colspan4 {
width: calc(100% - 92px);
}
Here's a working JSFiddle that I've made with some CSS modifications.
You need to put them inside div containers (block level elements)
<form>
<div class="panel-heading">
<h3 class="panel-title">Owner</h3>
</div>
<div>
<label for="firstName">Name</label>
<input name="firstName" type="text" class="colspan2"/>
<input name="lastName" type="text" class="colspan2"/>
</div>
<div>
<label for="street">Street</label>
<input name="street" type="text" class="colspan4"/>
</div>
<div>
<label for="zipCode">ZipCode</label>
<input name="zipCode" type="text" class="colspan1"/>
<input name="town" type="text" class="colspan3"/>
</div>
Upvotes: 1