Styling form elements with CSS can actually be a little bit tricky if we don't understand how these elements work. First of all, the
overwhelming majority of form controls are inline-block
elements. This set includes text fields, radio and checkbox buttons,
the select
element and
the textarea
element. Another thing to bear in mind is that the overall dimensions of one of these form controls are actually
determined by the font in use on such elements (including family and size).
Now let's start with a basic blog form for posting comments, like this:
<form action="" method="post"> <ul> <li> <label for="name">Name</label> <input type="text" name="name" id="name" /> </li> <li> <label for="email">E-mail</label> <input type="text" name="email" id="email" /> </li> <li> <label for="website">Website</label> <input type="text" name="website" id="website" /> </li> <li> <label for="comment">Comment</label> <textarea name="comment" id="comment" cols="15" rows="20"></textarea> </li> </ul> <p><input type="submit" name="submit" id="submit" value="Send" /></p> </form>
Note that we're using an unordered list to group our form elements. This makes a lot easier to use simple selectors and cascade, as shown below:
form { margin: 0; height: 100%; padding: 0.5em; border: 1px solid #999; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; font-size: 1.3em; } form ul { margin: 0; padding: 0.3em; list-style: none; height: 100%; background: #eee; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; } form ul li { height: 100%; padding-bottom: 0.5em; overflow: hidden; } form ul li label { float: left; display: block; width: 5em; padding-right: 0.5em; font-weight: bold; } form ul li input { float: left; display: block; width: 140px; border: 1px solid #cbcbbb; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; background: #fff; font: 1em Arial, Helvetica, sans-serif; } form ul li textarea { float: left; width: 300px; height: 250px; display: block; border: 1px solid #cbcbbb; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; background: #fff; font: 1em Arial, Helvetica, sans-serif; overflow: auto; } form p { padding: 0.5em 0; margin: 0; } form p input { background: #999; font-weight: bold; color: #fff; border: 1px solid #cbcbbb; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; }
The only thing to note here is the fact that we've specified a font on the input
and textarea
elements, except for the submit button. Note also how this element looks smaller than the others. You can see the final result below.