Home Programming Basic knowledge for using labels in HTML!

Basic knowledge for using labels in HTML!

by Yasir Aslam
0 comment

Among the elements that can be used in HTML, there is an element called “label” .
This is read as a “label” as it is, and is an element that exists as an inline element like a “span”.

icon 2488093 640

Table of contents

  • Difference between span and label
  • Convenient use of labels
    • Code to display radio buttons
    • Change to code using labels
  • How to set labels
  • summary

Difference between span and label

span is an inline element that can be used for general purposes, but label is mainly used to specify the item name .
The most common usage is to use it with an “input” element as a set to operate as a “label” for that “input” element.

Convenient use of labels

To see how to use labels, let’s first create HTML that displays radio buttons without using labels.

Code to display radio buttons

When I run this, as you can see in the video below, if I want to select each radio button, I have to click the circle of the radio button, and even if I select a character, it doesn’t get selected.

Change to code using labels

What happens if we rewrite this as HTML code using labels?

By selecting a letter, you can see that the choices have changed.
In this way, by setting the “label” for the radio button, it becomes possible to extend the selection range.

How to set labels

Labels are mainly used in combination with “input” elements. The key then is the “for” attribute .
By setting the “for” attribute to the same name as the “id” attribute of the “input” element, you can associate the label with the “input” element.

Conversely, if you mistake the names of the “for” and “id” attributes, it will not work properly.
Let’s look at an example of what went wrong.

As in the sample, if you select “Option 1”, “Option 2” will be selected, and if you select “Option 2”, “Option 1” will be selected.
Especially when you use a lot of labels, it is easy to make a mistake if you forget to copy the code and fix it, so be careful.

summary

Introduced how to use labels in HTML.

  • The label can associate the item name and the “input” element
  • Use the “label” element in combination with the “for” attribute
  • Link by making the “for” attribute of the “label” element the same as the “id” attribute of the “input” element

Labels can be used easily if you learn a few tricks, so please try using them to create an easy-to-use screen.

You may also like

Leave a Comment