Tip: Styling the label element with CSS

A few days ago I wrote  Tip: Styling a Fieldset with CSS. I decided to add to the small form I used and provide another tip on how to style the label element.

I made a few changes to the HTML example I’d used in the previous example. Here’s the new HTML page, with CSS. The changes result in this appearance for the form.

the styled labels in the form

In the HTML, I changed the labels to include the “for” attribute, so that I could move the closing label tags from where they before. The code is now like this for each label:

<label for="name">Your Full Name</label>
<input type="text" name="name" id="name" />

I also moved the submit button out of the fieldset, since it really didn’t belong in there in the first place.

I added the CSS to make the input fields appear as you see in the image (or on the example page). I made the labels display as block level elements, which were floated to the left. Then I assigned a width to the labels so that the input fields would all be a uniform distance away from the labels. I assigned a color and made the text bold. I used generated content to add a colon ( : ) after the label. (The colon may not appear in every browser.) Here’s the CSS.

label {
color: #B4886B;
font-weight: bold;
display: block;
width: 150px;
float: left;
}
label:after { content: ": " }

Those are the only changes needed to the form as it was described in the post about  Styling a Fieldset with CSS.

10 thoughts on “Tip: Styling the label element with CSS

  1. Pingback: Web Teacher › Tip: Styling the label element with CSS | Best Web Gallery

  2. I’m trying to style One Single label, not all… how can I target this
    Ship to billing address?

    from my style sheet… :)

    Thanks!

  3. You can also use a class name to target a specific label.
    HTML:

    Your Full Name

    CSS:
    .custom-label label {
    color: #B4886B;
    font-weight: bold;
    display: block;
    width: 150px;
    float: left;
    }

    • The html code got triggered by the page: Here it is again:
      ^div class=”custom-label”>
      ^label for=”name”>Your Full Name^/label>
      ^input type=”text” name=”name” id=”name” />
      ^/div>

      Replace “^” with “<"

Leave a Reply