Horizontally Align Labels with CSS - html

I've got an issue that I'd love to solve by using CSS without resorting to statically sizing my labels (but perhaps it isn't possible).
I have two labels per line, one for displaying a "title" and the other for displaying the associated "value". Here's how I'd like it to look:
This is similar to Align labels in form next to input but I'm wanting the second element per line left-aligned instead of the first one to be right-aligned. I tried modifying the accepted answer from that question and set the width of the "title" label, but that has no effect on my output. As I mentioned above, I'd rather not hard-code a width anyways, but I was hoping to get something working before trying to find a good, long-term solution that can account for larger "title" values.
Here's my current CSS (the classes should be self-explanatory):
.propertyTitle {
text-transform: uppercase;
width: 300px;/*Why doesn't this have any effect?*/
}
.propertyValue {
text-align: left;
}
And my current HTML:
<div>
<div>
<label class="propertyTitle">Hello:</label>
<label class="propertyValue">World</label>
</div>
<div>
<label class="propertyTitle">Goodbye:</label>
<label class="propertyValue">To All of the People in the World</label>
</div>
<div>
<label class="propertyTitle">I Want:</label>
<label class="propertyValue">These labels to line up</label>
</div>
</div>
The HTML can be modified as well, if that'd make it easier. To conform with best practices, I'd rather not use tables to make this work.
Here's a jsFiddle showing what I have now, what am I missing? Ideally this solution would work for IE8+ and Firefox, so unfortunately HTML5 and CSS3 elements are discouraged.
EDIT
To reiterate after the first two answers came in (that both solve my issue), is there a way to do this without hard-coding a width for my "title" labels?

grouping your divs and labels like so:
<div>
<div class="titleWrap">
<label class="propertyTitle">Hello:</label>
<label class="propertyTitle">Goodbye:</label>
<label class="propertyTitle">I Want:</label>
</div>
<div class="valueWrap">
<label class="propertyValue">World</label>
<label class="propertyValue">To All of the People in the World</label>
<label class="propertyValue">These labels to line up</label>
</div>
</div>
with the following CSS:
.propertyTitle {
display:block;
text-transform: uppercase;
width: auto;
}
.titleWrap{
display:inline-block;
}
.propertyValue {
display:block;
width:auto;
}
.valueWrap {
display:inline-block;
}
should give you the desired result without having to specify the widths
Check out this jsFiddle

try using display:inline-block on your labels
.propertyTitle {
text-transform: uppercase;
width: 300px;/*Why doesn't this have any effect?*/
display: inline-block;
}

by default label is an inline element. that's why width property doesn't apply to label.
to apply the width you have to convert the label into a block level element by using display:block.
I hope it clarify the answer.
so you have to use this CSS property in your code.
.propertyTitle {
text-transform: uppercase;
display:inline-block; /*this will make the label a block level element*/
width: 300px;/*Why doesn't this have any effect?*/
}

More modern version is display: inline-flex;

Related

Styling HTML <li> elements: avoiding an invalid parent <div>

The situation:
I have a site with a long list of questions across multiple pages.
Each question is within a made up of a label and an input. Groups of question divs are within an additional div to provide grouping and bordering styles, etc.
The problem:
I want to number my questions, but want to avoid hard coding the numbering. However, it is invalid html to place the <li> inside the divs or labels.
In addition some question divs are conditionally hidden and revealed depending on user input. The divs therefore provide key functionality, and the number must be hidden and revealed along with these divs, (so positioning each <li> outside a divs would be problematic.
Code:
Here is an example of a pared down structure of my form, showing two question "blocks":
<form id="myform" method="post" action="/destinaion/page.php">
<div class="formfield">
<div class="page1">
<div class="lowerborder">
<div class="question">
<label for="q2">Question 1</label>
<input type="number" id="q1" name="q1"/>
</div>
<div class="question">
<label for="q1">Question 2</label>
<input type="number" id="q2" name="q2"/>
</div>
</div>
</div>
</div>
</form>
The div class form field contains the form page, and page1 various styling particulars for page 1.
I'd like to make an ordered list from my questions, perhaps something like
Attempt at achieving goal:
<form id="myform" method="post" action="/destination/page.php">
<div class="formfield">
<ol>
<div class="page1">
<div class="lowerborder">
<div class="question">
<label for="q2"><li>Question 1</li></label>
<input type="number" id="q1" name="q1"/>
</div>
<div class="question">
<label for="q1"><li>Question 2</li></label>
<input type="number" id="q2" name="q2"/>
</div>
</div>
</div>
</ol>
</div>
</form>
But as you can see I am putting the <li> inside the <label> which a) is not valid html, and b) doesn't play well with all browsers.
How can I avoid putting <li> elements inside invalid parents, when my list items are separated by many nested divs?
jsFiddle:
See a fiddle of my above attempt. Including some styling and functionality I am trying to achieve (styling via nested divs, hidden questions that reveal etc)
Please see this fiddle demonstrating how to do everything you want without interposing any other elements. I found no need for even a single div anywhere.
Note: I initially used float:left for the question to make the answers line up properly. However, this caused IE to render the numbers just left of the answers instead of left of the questions. I switched to using display:inline-block and now everything works in IE as well.
Comments:
I cleaned up the style sheet, which had some sections repeated and conflicting style rules. I removed unnecessary rules.
I created the lines separating groups of questions using a class, and I also made it apply to the top border of a question rather than the bottom, so that you can use it even if there are hidden questions ending a group, since a hidden question would probably never begin a group. There was no need for additional elements to have borders.
In my opinion the label for the "Reveal" checkbox should be the text next to it, so that you can click that text to check and uncheck the box. Thus, I added a "question" class to the items that are the question, rather than using a label. You must apply the style "question" to the questions to make them style properly. You can apply that to a label element (which is for something else or not), or you can use a span or other element to contain the text when it is not a label.
IE 7 stupidly puts the numbers at the bottom of the line, even though the questions are styled with vertical-align:top. I don't know how to fix that at this time, but it could be another question to those more expert than I in CSS quirks.
IE was not handling the "hidden" method very well, taking up extra space and then when revealing not showing the child elements, so I used absolute positioning instead (which, by taking it out of the document flow, has the same effect). See the CSS for how it works.
I modified the way you were applying the reveal script. Instead of manually wiring up each individual item, instead I put a data value on the checkbox itself, then at the ready event I use that to wire up the page appropriately. Now you can have checkboxes that reveal more questions just by adding an id to the revealed question (or use class instead if you need to reveal more than one at a time) and a data expando attribute like data-togglehidden="l4" to specify the id to toggle right in the checkbox element. No script changes required.
It looks a little like you may have "div-itis" which is the tendency to multiply divs all over the place. No need to be embarrassed, I have had div-itis too, when I was new to html development. You'll grow out of it due to experiences like this. In general, you should use normal non-div page elements and style them directly, rather than wrap things in divs and styling those. Divs are useful when you need to style a group of related functionality or provide a box for different elements. One hint that you may be using divs improperly is when they only have a single item in them (especially another div). Sometimes that is necessary, but ask yourself: can I move the style to the parent or child element instead?
I need to know more about how the "pages" work that you mentioned and that were in your original html markup. There are no pages in html, only when html is printed. So I'm not quite sure what that means or how to style your pages for you.
Here is the cleaned-up html, without the need of additional elements between ol and li:
<form id="myform" method="post" action="/destination/page.php">
<ol class="formfield">
<li>
<label class="question" for="q1">What is your first name?</label>
<input type="text" id="q1" name="q1"/>
</li>
<li>
<label class="question" for="q2">A very long question 2 that is sure to run to a second line just to prove that such a thing will work properly and not mess up the layout, described in your own words?</label>
<input type="text" id="q2" name="q2"/>
</li>
<li class="begingroup">
<span class="question">Are you the type of person who likes to needlessly answer extra questions?</span>
<input type="checkbox" id="q3" name="q3" data-togglehidden="l4"/>
<label for="q3">Yes, yes, that's me!!!</label>
</li>
<li id="l4" class="hidden">
<label class="question" for="q4">Why do you like to do extra needless work?</label>
<input type="text" id="q4" name="q4"/>
</li>
<li class="begingroup">
<label class="question" for="q5">What was your first pet's name?</label>
<input type="text" id="q5" name="q5"/>
</li>
</ol>
</form>
Here's what it looks like in Firefox 16.0.2:
And in IE 7.0.5730.13CO:
The CSS:
ol.formfield {
width: 500px;
margin: 10px auto;
padding: 16px 16px 16px 0;
border: 5px groove #005E9B;
list-style: decimal outside;
color: black;
background-color: #6Fc2F7;
font-family: 'Oxygen', sans-serif;
font-size:15px;
}
ol.formfield li {
clear: both;
padding: 2px;
margin-left: 1.7em;
}
ol.formfield li.begingroup {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid #005E9B;
}
.question {
display:inline-block;
width:300px;
vertical-align:top;
}
.hidden {
position: absolute;
height: 0;
width: 0;
overflow: hidden;
}
ol.formfield input {
border-radius:5px; /* css 3 */
-moz-border-radius:5px; /* mozilla */
-webkit-border-radius:5px; /* webkit */
}
And the script to wire up your hide/reveal based on data values on elements:
$('ol.formfield input:checkbox')
.each(function() {
var d = $(this).data('togglehidden');
if(d) {
$(this).on('change', function() {
if ($(this).attr('checked')) {
$('#' + d)
.removeClass('hidden')
.find(':input')
.focus();
} else {
$('#' + d).addClass('hidden');
}
});
}
});

Is such alignment achievable without <table>?

My goal is an alignment as shown in the attached image (the fields on the left may have any width, but the ones on the right should begin at the same X coordinate).
Right now I am using a simple table code to achieve this:
<table><tr>
<td>Left1</td><td>Right 1</td></tr>
<tr><td>Left 2</td><td>Right 2</td></tr></table>
However, I've heard that using tables is generally bad. Is there a way I could achieve the same design using CSS? The website is being designed for mobile devices which might not support fancy CSS, so the code must be as simple as possible.
EDIT: since I still occasionally get a notification on this question from people who (presumably) are just starting out with HTML like I was when I made it, please refer to the accepted answer by B T as this is by far the best way to achieve this functionality. The question suggested as a "possible duplicate" (31 May 2016) does not currently offer the table-row/table-column CSS-based approach and requires you to do guess work.
I found a much easier way to do this by accident. Say you have the following:
<div class='top'>
<div>Something else</div>
<div class='a'>
<div>Some text 1</div>
<div>Some text 2</div>
</div>
<div class='a'>
<div>Some text 3</div>
<div>Some text 4</div>
</div>
</div>
You can align Some text 1 and Some text 2 using css table display styling like this:
.a {
display: table-row;
}
.a div {
display: table-cell;
}
The coolest thing is that as long as the 'top' div is NOT styled display: table, then other things like "Something else" can be ignored in terms of alignment. If the 'top' div IS styled display: table, then "Some text 1" will be aligned with "Something else" (ie it treats all its children like table rows, even if they have a different display style).
This works in Chrome, not sure if its supposed to behave this way, but I'm glad it works.
.a {
display: table-row;
}
.a div {
display: table-cell;
}
<div class='top'>
<div>Something else</div>
<div class='a'>
<div>Some text 1</div>
<div>Some text 2</div>
</div>
<div class='a'>
<div>Some text 3</div>
<div>Some text 4</div>
</div>
</div>
While it is possible to achieve the same with tables, it would be considered semantically incorrect to use a table for the purpose of layout. Especially since you can achieve the same using just a line or two of CSS.
Give your labels a fixed width (something larger than your longest label text).
<style>
label {
width: 100px;
display: inline-block;
}​
</style>
<label>Name</label>
<input type="text" />
<br/>
<label>Email Address</label>
<input type="text" />​
Example
Here, you could use this for getting the output required.
Using tables IMO is not bad practice, in fact they should be used where tabular data is required, or the format of data resembles a table.
However, designing a full page, or anything not to be displayed in a tabular format, using a table is discouraged, and is in fact very very wrong.
Here goes a sample using a non-table structure:
HTML :
<form>
<label for="name">Email: </label><input id="name" type="email" placeholder="#" />
<br/><br />
<label>Password: </label><input type="password" id="password" placeholder="*"/>
</form>
CSS:
label {
width: 80px;
display: block;
vertical-align: middle;
float:left;
clear:left;
}
input {
border-top-left-radius:5px;
border-bottom-right-radius: 10px;
background: #141414;
color: #fdd56c;
outline: none;
}
Here is an example
Yes, such alignment is possible. Using CSS classes, you can markup your HTML in such a way to achieve the same look of a table without the headache of using a table (or making the markup look ugly).
Using this CSS:
.label {
display: inline-block;
width: 100px;
}
.inputBox {
width: 200px;
}
and this HTML:
<span class="label">E-mail:</span><input type="email"></input><br>
<span class="label">Password:</span><input type="text"></input>
you'll get the layout you want.
To do this with IE7 support, change the CSS above to this:
.label {
display: block;
width: 100px;
float: left;
clear: left;
}
Then, add this line below the lines already shown:
<div style="clear: left"></div>
Example using IE7-compatible settings: http://jsfiddle.net/bbXXp/
True. I am learning it the hard way. I used table for alignment, and now, certain alignments are becoming bizzare in smaller screens (e.g. mobile phone, tablets etc). Hence, am switching over to div. Preferable use <div style="display:inline-block">...</div>, which will align automatically if the screen is smaller.
Hence, my advice is that Table should be used only for genuine tables, and not for aligning controls in a body.

Differents way to structure html inputs and labels in a form

I'm wondering what are the best solutions to structure a html form with labels and inputs.
I used to do this with float: left to the label and float: right for the inputs. And each line is surround with a block clear: both.
But i don't think these CSS property were made for something like that..
So what are the others solutions ? Tables ?
Well it really depends on what you want the form to look like. For example, if you want a clear grid with borders I recommend using a table.
To duplicate what you have, you can do this:
<label for='textbox'>Label</label><input type='text' id='textbox' />
And then this css:
label { display: inline-block; width: 100px; }
This will make the label stay on the same line as in input element but will push it the appropriate distance.
Personally, I try to avoid using floats to align elements. I would rather use position absolute and set left or right and top or bottom. To me floating is like asking the browser to do it for you, and maybe some browsers (cough ie cough) will decide to draw it a little differently.
Form markup and CSS will always be a personal choice. Sure, there are some rights and wrongs semantically and technically from a CSS point of view, but there certainly isn't one (or even a few) "right" techniques.
My personal preference is to float the label left and contain my inputs inside lists, which I personally consider more semantic than a div or p tag.
HTML:
<form>
<fieldset>
<ol>
<li>
<label for="input1">Label 1</label>
<input type="text" name="input1" id="input1">
</li>
<li>
<label for="input2">Label 2</label>
<input type="text" name="input2" id="input2">
</li>
<li>
<label for="input3">Label 3</label>
<input type="text" name="input3" id="input3">
</li>
</ol>
<button type="submit">Submit</button>
</fieldset>
</form>
CSS:
li {
clear: left;
margin-bottom: 10px;
}
label {
float: left; /* You could use "display: inline-block;" instead. */
margin-right: 10px;
width: 80px;
}
tables is also a solution.
also , Div with 2 inner divs( left and right)
or 1 div with both elements with float:left with margin-left.

How to make a whole 'div' clickable in html and css without JavaScript? [duplicate]

This question already has answers here:
Make a div into a link
(30 answers)
Closed 9 years ago.
I want to make it so that a whole div is clickable and links to another page when clicked without JavaScript and with valid code/markup.
If I have this which is what I want the result to do -
<a href="#">
<div>This is a link</div>
</a>
The W3C validator says that block elements shouldn't be placed inside an inline element. Is there a better way to do this?
It is possible to make a link fill the entire div which gives the appearance of making the div clickable.
CSS:
#my-div {
background-color: #f00;
width: 200px;
height: 200px;
}
a.fill-div {
display: block;
height: 100%;
width: 100%;
text-decoration: none;
}
HTML:
<div id="my-div">
</div>
<div onclick="location.href='#';" style="cursor: pointer;">
</div>
a whole div links to another page when clicked without javascript and
with valid code, is this possible?
Pedantic answer: No.
As you've already put on another comment, it's invalid to nest a div inside an a tag.
However, there's nothing preventing you from making your a tag behave very similarly to a div, with the exception that you cannot nest other block tags inside it. If it suits your markup, set display:block on your a tag and size / float it however you like.
If you renege on your question's premise that you need to avoid javascript, as others have pointed our you can use the onClick event handler. jQuery is a popular choice for making this easy and maintainable.
Update:
In HTML5, placing a <div> inside an <a> is valid.
See http://dev.w3.org/html5/markup/a.html#a-changes (thanks Damien)
Without JS, I am doing it like this:
My HTML:
<div class="container">
<div class="sometext">Some text here</div>
<div class="someothertext">Some other text here</div>
text of my link
</div>
My CSS:
.container{
position: relative;
}
.container.a{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-indent: -9999px; //these two lines are to hide my actual link text.
overflow: hidden; //these two lines are to hide my actual link text.
}
My solution without JavaScript/images. Only CSS and HTML. It works in all browsers.
HTML:
<a class="add_to_cart" href="https://www.example.com" title="Add to Cart!">
buy now<br />free shipping<br />no further costs
</a>
CSS:
.add_to_cart:hover {
background-color:#FF9933;
text-decoration:none;
color:#FFFFFF;
}
.add_to_cart {
cursor:pointer;
background-color:#EC5500;
display:block;
text-align:center;
margin-top:8px;
width:90px;
height:31px;
border-radius:5px;
border-width:1px;
border-style:solid;
border-color:#E70000;
}
Nesting block level elements in anchors is not invalid anymore in HTML5. See http://html5doctor.com/block-level-links-in-html-5/ and http://www.w3.org/TR/html5/the-a-element.html.
I'm not saying you should use it, but in HTML5 it's fine to use <div></div>.
The accepted answer is otherwise the best one. Using JavaScript like others suggested is also bad because it would make the "link" inaccessible (to users without JavaScript, which includes search engines and others).
jQuery would allow you to do that.
Look up the click() function:
http://api.jquery.com/click/
Example:
$('#yourDIV').click(function() {
alert('You clicked the DIV.');
});
Well you could either add <a></a> tags and place the div inside it, adding an href if you want the div to act as a link. Or else just use Javascript and define an 'OnClick' function. But from the limited information provided, it's a bit hard to determine what the context of your problem is.
.clickable {
cursor:pointer;
}
Something like this?
<div onclick="alert('test');">
</div>
AFAIK you will need at least a little bit of JavaScript...
I would suggest to use jQuery.
You can include this library in one line. And then you can access your div with
$('div').click(function(){
// do stuff here
});
and respond to the click event.
we are using like this
<label for="1">
<div class="options">
<input type="radio" name="mem" id="1" value="1" checked="checked"/>option one
</div>
</label>
<label for="2">
<div class="options">
<input type="radio" name="mem" id="2" value="1" checked="checked"/>option two
</div></label>
using
<label for="1">
tag and catching is with
id=1
hope this helps.

CSS : Table with Labels and Text Boxes

I am trying to break the table crutch...
I want to place 3 "labels", "First", "Middle" and "Last" over 3 text boxes so that the labels are above the corresponding text boxes and the labels and text boxes are vertically aligned. In other words, I need a 3 columns table where the first row has 3 labels and the 2nd row has 3 text boxes in them and everything is left justified and I want ALL the columns widths to be identical and fixed.
How do I do this with w/o tables using only CSS?
I know that margin-left will give me a consistent distance between the groups, but how do I "carriage return" to the next line w.o using a Paragraph or a break tag, since the distance involved is really a function of the font, I imagine, instead of being able to "carriage return down" a specified number of pixels.
I know that display: block will put things on a new line, but that creates a break before and after. I just want a break "after."
I hope I explained it well enough.
Thanks.
Additional Edit:
I understand that perhaps I should not be avoid using tables for something that tables is good at, but if CSS had an attribute analagos to margin-left:10px but in a vertical direction AFTER performing a cariage return, the advantage of using CSS over tables is that I wouldn't have a million TR and TD tags in my markup.
Is there such a thing?
What you do is create your form fields this way:
<div id="form">
<div class="control">
<div class="label">
<label for="field1">Field 1</label>
</div>
<div class="field">
<input type="text" name="field1" id="field1">
</div>
</div>
...
</div>
with:
#form { overflow: hidden; } // this is important!
#form div.control { float: left; width: 33%; }
Now if one of those labels is larger the controls won't line up but this would be an example of where "pure" CSS falls shorts of what tables can do easily and naturally, which begs the question: why are you giving up on tables?
Note: Another answer along the same lines has suggested not wrapping the label and input in a div. This is a reasonable approach but you lose some expressive power. For instance, some things in CSS are only possible on block level elements. For example, you could change the above with:
#form, div.control { overflow: hidden; width: 600px } // this is important!
#form div.control { float: left; width: 200px; }
#form div.control div { float: left; width: 100px; }
and get your labels on the left, which you can't do quite as well without the wrapping inner divs.
HTML:
<div class="row">
<div class="column">
<label>Left</label>
<input name="left" />
</div>
<div class="column">
<label>Left</label>
<input name="left" />
</div>
<div class="column">
<label>Left</label>
<input name="left" />
</div>
</div>
CSS:
.row .column{
width: 200px;
float:left;
}
.row .column input,
.row .column label{
display:block;
}
You can now use CSS to style the textboxes and labels, so they look nice. Also notice how similar this example is to using tables, which goes to show that in some scenarios tables aren't evil, but the right way to go. If you want to align things in a grid, use tables.
Turns out that if you want to make a table of labels over input fields, the table element is fine to use.... If the table element is the clearest html code, why not use it?