Как изменить цвет label html

Тег

Тег <label> определяет текстовую метку для тега <input>. Метка представляет собой обычный текст, кликнув по которому, пользователь может выбрать элемент формы. Она облегчает использование формы, так как в элементы формы не всегда удобно попасть курсором.

Тег <label> парный, текст размещается между открывающим (<label>) и закрывающим (</label>) тегами.

Тег <label> также используется для определения горячих клавиш на клавиатуре и перехода на активный элемент подобно ссылкам.

Связать текстовую метку и форму, к которой она относится, можно двумя способами:

  1. установить идентификатор id внутри элемента <input> и указать его имя в качестве атрибута for тега <label>.

Пример

<!DOCTYPE html>
<html>
   <head>
      <title> Заголовок документа</title>
   </head>
   <body>
          <form>
              <label for="lfname">Имя пользователя:</label> 
              <input id="lfname" name="fname" type="text" />
          </form>
   </body>
</html>

Результат

labelexample1

  1. Поместить <input> в элемент <label>.

Пример

<!DOCTYPE html>
<html>
   <head>
      <title>Заголовок документа</title>
   </head>
  <body>
    <form>
      <label>Имя
      <input id="User" name="Имя" type="text" />
      </label>
    </form>
  </body>
</html>

Результат

labelexample2

Пример (форма с флажками)

<!DOCTYPE html>
<html>
   <head>
      <title>Заголовок документа</title>
   </head>
   <body>
          <form>
              <label for="barca">Барселона</label>
              <input type="radio" name="team" id="barca" value="Барселона"><br />
              <label for="real">Реал Мадрид</label>
              <input type="radio" name="team" id="real" value="Реал Мадрид"><br />
          </form>
   </body>
</html>

Результат

labelexample3

Используйте CSS свойства font для стилизации тега <label>.

Пример

<!DOCTYPE html>
<html>
  <head>
    <title>Заголовок документа</title>
    <style>
      body {
       padding: 20px;
      }
      label {
        font-size: 20px;
        font-weight: 700;
        color: #1c87c9;
      }
      input {
        width: 50%;
        height: 28px;
        padding: 4px 10px;
        border: 1px solid #666;
        background: #cce6ff;
        color: #1c87c9;
        font-size: 16px;
      }
    </style>
  </head>
  <body>
    <form>
      <label>Ваше имя:</label>
      <input id="User" name="Name" type="text"/>
    </form>
  </body>
</html>

Результат

labelexample4

Тег <label> поддерживает глобальные атрибуты и атрибуты событий.

Asked
7 years, 3 months ago

Viewed
89k times

I am using checkbox type coding and I would like to make it so that for specific options, I am able to click it and it turns blue, and for other options, I can click it and it will turn red or green. I have found a way to do this, as shown in the CSS, but I figured I would have to keep writing code for each type of label. So I was wondering if there was a much more efficient way of doing this? Thanks. Here is the code:

input[type="checkbox"] {
	display: none;
}

label {
	cursor: pointer;
	color: #555;
	display: block;
	padding: 10px;
	margin: 3px;
}

input[type="checkbox"]:checked + label {
	color: #ffffff;
	font-weight: bold;
    background: blue;
}

input[type="checkbox"]:checked + label[for=red1] {
	color: #ffffff;
	font-weight: bold;
    background: red;
}

input[type="checkbox"]:checked + label[for=red2] {
	color: #ffffff;
	font-weight: bold;
    background: red;
}

input[type="checkbox"]:checked + label[for=green1] {
	color: #ffffff;
	font-weight: bold;
    background: green;
}
<div><input id="blue1" type="checkbox" /><label for="blue1">1 blue</label></div>
<div><input id="blue2" type="checkbox" /><label for="blue2">2 blue</label></div>
<div><input id="blue3" type="checkbox" /><label for="blue3">3 blue</label></div>
<div><input id="blue4" type="checkbox" /><label for="blue4">4 blue</label></div>
<div><input id="red1" type="checkbox" /><label for="red1">1 red</label></div>
<div><input id="red2" type="checkbox" /><label for="red2">2 red</label></div>
<div><input id="green1" type="checkbox" /><label for="green1">1 green</label></div>

asked Nov 4, 2015 at 0:14

doglover123's user avatar

You can use the CSS ‘starts with’ attribute selector (^=) to select all labels with a for attribute that starts with ‘red’, ‘green’, etc.

input[type="checkbox"] {
    display: none;
}

label {
    cursor: pointer;
    color: #555;
    display: block;
    padding: 10px;
    margin: 3px;
}

input[type="checkbox"]:checked + label {
    color: #ffffff;
    font-weight: bold;
    background: blue;
}

input[type="checkbox"]:checked + label[for^=red] {
    color: #ffffff;
    font-weight: bold;
    background: red;
}

input[type="checkbox"]:checked + label[for^=green] {
    color: #ffffff;
    font-weight: bold;
    background: green;
}

answered Nov 4, 2015 at 0:26

collinksmith's user avatar

collinksmithcollinksmith

5401 gold badge5 silver badges14 bronze badges

    label { color: red; }
    label span { color: green; }
<label> Label <span>Text with other color</span> </label>

answered Aug 11, 2021 at 4:39

For one, you don’t have to repeat the color and font-weight styles from the first input[type="checkbox"]:checked + label.

An option would be to have classes for the different types of labels, for example:

input[type="checkbox"]:checked + label {
  color: #fff;
  font-weight: bold;
}

input[type="checkbox"]:checked + .blue {
  background: blue;
}

input[type="checkbox"]:checked + .red {
  background: red;
}

...

Then your HTML:

<div><input id="blue1" type="checkbox" /><label for="blue1" class="blue">1 blue</label></div>
<div><input id="blue2" type="checkbox" /><label for="blue2" class="blue">2 blue</label></div>
<div><input id="blue3" type="checkbox" /><label for="blue3" class="blue">3 blue</label></div>
<div><input id="blue4" type="checkbox" /><label for="blue4" class="blue">4 blue</label></div>
<div><input id="red1" type="checkbox" /><label for="red1" class="red">1 red</label></div>
<div><input id="red2" type="checkbox" /><label for="red2" class="red">2 red</label></div>
<div><input id="green1" type="checkbox" /><label for="green1" class="green">1 green</label></div>

Further optimization would require some CSS preprocessor, such as SASS.

input[type="checkbox"]:checked {
  + label {
    color: #fff;
    font-weight: bold;
  }

  + .blue {
    background: blue;
  }

  ...
}

answered Nov 4, 2015 at 0:26

Will's user avatar

WillWill

19.3k7 gold badges47 silver badges48 bronze badges

The <label> HTML element represents a caption for an item in a user interface.

Try it

Associating a <label> with a form control, such as <input> or <textarea> offers some major advantages:

  • The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screen reader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
  • When a user clicks or touches/taps a label, the browser passes the focus to its associated input (the resulting event is also raised for the input). That increased hit area for focusing the input provides an advantage to anyone trying to activate it — including those using a touch-screen device.

To explicitly associate a <label> element with an <input> element, you first need to add the id attribute to the <input> element. Next, you add the for attribute to the <label> element, where the value of for is the same as the id in the <input> element.

Alternatively, you can nest the <input> directly inside the <label>, in which case the for and id attributes are not needed because the association is implicit:

<label>
  Do you like peas?
  <input type="checkbox" name="peas" />
</label>

The form control that a label is labeling is called the labeled control of the label element. Multiple labels can be associated with the same form control:

<label for="username">Enter your username:</label>
<input id="username" name="username" type="text" />
<label for="username">Forgot your username?</label>

Elements that can be associated with a <label> element include <button>, <input> (except for type="hidden"), <meter>, <output>, <progress>, <select> and <textarea>.

Attributes

This element includes the global attributes.

for

The value of the for attribute must be a single id for a labelable form-related element in the same document as the <label> element. So, any given label element can be associated with only one form control.

Note: To programmatically set the for attribute, use htmlFor.

The first element in the document with an id attribute matching the value of the for attribute is the labeled control for this label element — if the element with that id is actually a labelable element. If it is not a labelable element, then the for attribute has no effect. If there are other elements that also match the id value, later in the document, they are not considered.

Multiple label elements can be given the same value for their for attribute; doing so causes the associated form control (the form control that for value references) to have multiple labels.

Note: A <label> element can have both a for attribute and a contained control element, as long as the for attribute points to the contained control element.

Styling with CSS

There are no special styling considerations for <label> elements — structurally they are simple inline elements, and so can be styled in much the same way as a <span> or <a> element. You can apply styling to them in any way you want, as long as you don’t cause the text to become difficult to read.

Examples

Defining an implicit label

<label>Click me <input type="text" /></label>

Defining an explicit label with the «for» attribute

<label for="username">Click me to focus on the input field</label>
<input type="text" id="username" />

Accessibility concerns

Interactive content

Don’t place interactive elements such as anchors or buttons inside a label. Doing so makes it difficult for people to activate the form input associated with the label.

Don’t

<label for="tac">
  <input id="tac" type="checkbox" name="terms-and-conditions" />
  I agree to the <a href="terms-and-conditions.html">Terms and Conditions</a>
</label>

Do

<label for="tac">
  <input id="tac" type="checkbox" name="terms-and-conditions" />
  I agree to the Terms and Conditions
</label>
<p>
  <a href="terms-and-conditions.html">Read our Terms and Conditions</a>
</p>

Headings

Placing heading elements within a <label> interferes with many kinds of assistive technology, because headings are commonly used as a navigation aid. If the label’s text needs to be adjusted visually, use CSS classes applied to the <label> element instead.

If a form, or a section of a form needs a title, use the <legend> element placed within a <fieldset>.

Don’t

<label for="your-name">
  <h3>Your name</h3>
  <input id="your-name" name="your-name" type="text" />
</label>

Do

<label class="large-label" for="your-name">
  Your name
  <input id="your-name" name="your-name" type="text" />
</label>

Buttons

An <input> element with a type="button" declaration and a valid value attribute does not need a label associated with it. Doing so may actually interfere with how assistive technology parses the button input. The same applies for the <button> element.

Technical summary

Content categories Flow content,
phrasing content,
interactive content,
form-associated element, palpable content.
Permitted content Phrasing content, but no descendant label elements. No
labelable
elements other than the labeled control are allowed.
Tag omission None, both the starting and ending tag are mandatory.
Permitted parents Any element that accepts
phrasing content.
Implicit ARIA role No corresponding role
Permitted ARIA roles No role permitted
DOM interface HTMLLabelElement

Specifications

Specification
HTML Standard
# the-label-element

Browser compatibility

BCD tables only load in the browser

Earn income with your HTML skills

Sign up and we’ll send you the best freelance opportunities straight to
your inbox.
We’re building the largest self-service freelancing marketplace for people like you.

A style attribute on a <label> tag assigns a unique style to the label.

Its value is CSS that defines the appearance of the label.

Example

#

A style attribute on a <label> element.

<form>
  <label style="color: teal;font-weight: 500;"
         for="firstname" >First name</label> &nbsp;
  <input type="text" id="firstname" name="firstname">
</form>

Using style

The style attribute specifies the style, i.e. look and feel, of the <label> element.

A style contains any number of CSS property/value pairs, separated by semicolons (;).

The style attribute overrides any other style that was defined in a <style> tag or an external CSS file.

This inline styling affects the current <label> element only.


Syntax

<label style="CSS-styles">

Values

#

Value Description
CSS-styles One or more CSS property/value pairs separated by semicolons (;).

More Examples

A style attribute on a <label> element.
Clicking the button toggles the text color.

<form>
  <label id="mylabel" style="color:teal;font-weight:500;"
         for="firstname" >First name</label> &nbsp;
  <input type="text" id="firstname" name="firstname">
</form>

<br />
<button onclick="toggle();">Toggle style</button>

<script>
  let toggle = () => {
    let element = document.getElementById("mylabel");

    if (element.style.color === "teal") {
       element.style.color = "tomato";
    } else {
       element.style.color = "teal";
    }
  }
</script>

Code explanation

The style attribute assigns a text color to the <label> element.

Clicking the button calls JavaScript which toggles the text color to another color.


Browser support

Here is when style support started for each browser:

Chrome

1.0 Sep 2008

Firefox

1.0 Sep 2002

IE/Edge

1.0 Aug 1995

Opera

1.0 Jan 2006

Safari

1.0 Jan 2003

You may also like

  • Our HTML label Tag Reference
  • Our HTML style Attribute Reference
  • Our CSS Text Tutorial

 Back to <label>

Earn income with your HTML skills

Sign up and we’ll send you the best freelance opportunities straight to
your inbox.
We’re building the largest self-service freelancing marketplace for people like you.

  • HTML Tables
  • HTML Images
  • HTML Color Names
  • HTML Links
  • HTML Tags
  • HTML Lists
  • HTML Forms
  • HTML Buttons
  • HTML Spaces
  • HTML Checkboxes
  • HTML Editors
  • HTML Comments

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    The HTML <input type=”radio”> is used to define a Radio Button. Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created by using the “input” element with a type attribute having value as “radio”.

    In this article, we will learn to style labels associated with selected radio input and checkboxes.

    Syntax:

    <input type="radio/checkbox">

    The HTML <input type=”checkbox”> is used to define a checkbox field. The checkbox is shown as a square box that is ticked when it is activated. It allows the user to select one or more options among all the limited choices.

    Now we will style the label of the radio buttons and checkboxes.

    Approach

    • We will first select the class/id of the div in which the label tag is used.
    • Then use the syntax:
    .className input[type="radio/checkbox"]: checked + label {
        // Whatever properties to be altered  
    }

    Example 1: In this example, we will style label of the radio buttons:

    HTML

    <html>

    <head>

        <title>Styling Label</title>

        <style>

            .radioButton input[type="radio"]:checked+label {

                background-color: green;

                color: white;

            }

        </style>

    </head>

    <body>

        <div class="radioButton">

            <p>Please select your favorite Web language:</p>

            <input type="radio" id="html" name="fav_language" 

                   value="HTML">

            <label for="html">HTML</label><br><br><br>

            <input type="radio" id="css" name="fav_language" 

                   value="CSS">

            <label for="css">CSS</label><br><br><br>

            <input type="radio" id="javascript" name="fav_language" 

                   value="JavaScript">

            <label for="javascript">JavaScript</label>

        </div>

    </body>

    </html>

    Output:

    Example 2: In this example, we will style the label of the checkboxes.

    HTML

    <html>

    <head>

        <title>Styling Label</title>

        <style>

            .checkBox input[type="checkbox"]:checked+label {

                background-color: green;

                color: white;

            }

        </style>

    </head>

    <body>

        <div class="checkBox">

            <p>Which language you can speak?:</p>

            <input type="checkbox" name="check" id="GFG" 

                   value="1" checked>

            <label> Hindi</label>

            <br>

            <input type="checkbox" name="check" value="2">

            <label> English</label>

            <br>

        </div>

    </body>

    </html>

    Output:

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить цвет input type radio
  • Как изменить цвет input range css
  • Как изменить цвет imgui lua
  • Как изменить цвет imessage
  • Как изменить цвет html текст

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии