- CSS for Labels, Buttons and Form Interactions
- Part 4: CSS for Labels, Buttons and Form Interactions
- Styling CSS Labels
- Styling Form Controls
- Aligning Labels to the Left of Inputs
- Styling Buttons in CSS
- Centering Form Elements
- Responding to Focus and Hover Events in CSS
- Going Forward
- Пример
- Результат
- Пример
- Результат
- Пример (форма с флажками)
- Результат
- Пример
- Результат
- Атрибуты
- Как добавить стиль к тегу ?
- Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :
- Цвет текста внутри тега :
- Стили форматирования текста для тега :
- Другие свойства для тега :
- Изменение фона label с помощью hover
- Решение
- How to style labels with CSS?
- Styling the labels
- Example: Styling the labels with CSS
- Output
- Example: styling the labels with CSS
- Conclusion
CSS for Labels, Buttons and Form Interactions
Part 4: CSS for Labels, Buttons and Form Interactions
In the last installment of this series on Web Forms, we explored some of the most commonly employed CSS attributes to style form elements. Today’s article continues from where that one left off to cover how to style labels and buttons, as well as how to alter an element’s appearance based on user interactions.
You can review the previous articles in this series by visiting:
Styling CSS Labels
In addition to adding functionality to your forms, labels can greatly increase readability and play a part in laying out form controls. To illustrate, let’s take a form that accepts user info, with the following HTML markup:
Styling Form Controls
That produces this bare-bones form:
Before we get to the labels, let’s apply a bit of styling to the form and input controls:
That first rule selects everything on the page using the asterisk (*) wildcard character. Hence, it applies the specified font-family to the entire page.
With the above styles in place, you’ll notice that the label positioning becomes haphazard, in that some appear above the input, while others are aligned to the left:
We can position all labels above their associated controls using the following CSS:
The key attribute is “display: block;”. Assigning a value of “block” to the display property makes the element behave as a block element, such as a . Hence, it starts on a new line, and takes up the entire width of the container. We can verify this behavior by inspecting a label with the browser tools:
The “label:after” creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. In our case, we can use it to append a colon (:) after each label.
Here is the form with all CSS applied:
Aligning Labels to the Left of Inputs
Another common layout is to position labels to the left of their associated controls. To do that, we can replace the “display: block;” with two other attributes, i.e. width and float:
The width determines how much horizontal space the label “column” takes. The more width is allocated, the further from the controls the labels will be.
Assigning a value of “left” to float positions labels to the left-most edge of their container.
There are a couple of other considerations when positioning labels to the left of their associated controls:
- Make sure that the form’s width is great enough to accommodate both the labels and fields on one line. Otherwise, they may wrap.
- You may want to assign a value to the margin-top so that there is a bit of vertical space between form elements. Without that, they can look like a stack of slices in a loaf of bread!
We’ll deal with both those issues by adding the following CSS:
Here is the updated form with labels to the left of input fields:
Styling Buttons in CSS
Without additional CSS styling, HTML buttons are rendered as gray rectangular boxes with black text. Not very interesting. The good news is that CSS allows us to change virtually every aspect of a button’s appearance and positioning. Case in point, take a look at the following CSS rule:
Now the button’s appearance matches the color palette of the rest of the form:
Centering Form Elements
One difference between the Submit button and the rest of the form is that it is horizontally centered. There are a number of ways to center an element within its container; one way is to give the element a width (either absolute or relative) and then set the margin-left and margin-right attributes to “auto”. Here is the code that centers the Submit button:
display: block; margin-left: auto; margin-right: auto; width: 80px;
Responding to Focus and Hover Events in CSS
You might be under the impression that you need JavaScript in order to make a form interactive. Not true! Thanks to the CSS :focus and :hover pseudo-classes, you can change an element’s appearance in response to user actions. As you may have guessed, the :focus pseudo-class governs an element’s appearance when it obtains the focus. Likewise, the :hover pseudo-class sets an element’s appearance when the mouse cursor traverses over it.
Here is a rule that alters the Submit button’s appearance on focus:
This rule kicks in when the mouse cursor is traverses over the Submit button:
You’ll find the demo for this tutorial on codepen.io.
Going Forward
In the next article, we’ll cover radio buttons, checkboxes, and selects before moving on to JavaScript and its role in making forms more interactive.
HTML тег
Тег
Тег также используется для определения горячих клавиш на клавиатуре и перехода на активный элемент подобно ссылкам.
Связать текстовую метку и форму, к которой она относится, можно двумя способами:
Пример
html> html> head> title> Заголовок документа title> head> body> form> label for="lfname">Имя пользователя: label> input id="lfname" name="fname" type="text" /> form> body> html>
Результат
Пример
html> html> head> title>Заголовок документа title> head> body> form> label>Имя input id="User" name="Имя" type="text" /> label> form> body> html>
Результат
Пример (форма с флажками)
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>
Результат
Используйте CSS свойства font для стилизации тега .
Пример
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>
Результат
Атрибуты
Атрибут | Значение | Описание |
---|---|---|
accesskey | accesskey | Определяет горячую клавишу, с помощью которой можно перейти к привязанному к метке (через атрибут for) элементу формы. |
for | element_id | Устанавливает идентификатор элемента, к которому должна быть привязана метка. |
form | form_id | Определяет форму (формы) с которой будет связана метка. Этот атрибут позволяет размещать метки в произвольном месте документа, а не только в качестве потомка элемента тега . Элемент был удален из спецификации HTML. |
Как добавить стиль к тегу ?
Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :
- CSS свойство font-style задает стиль шрифта: normal | italic | oblique | initial | inherit
- CSS свойство font-family создает приоритетный список названий семейства шрифтов и/или общее имя шрифтов для выбранных элементов.
- CSS свойство font-size задает размер щрифта.
- CSS свойство font-weight устанавливает насыщенность шрифта.
- CSS свойство text-transform задает регистр текста (заглавные или строчные буквы).
- CSS свойство text-decoration устанавливает оформление текста. Оно является сокращенным свойством для text-decoration-line, text-decoration-color, text-decoration-style.
Цвет текста внутри тега :
Стили форматирования текста для тега :
- CSS свойство text-indent указывает размер отступа первой строки в текстовом блоке.
- CSS свойство text-overflow указывает, как будет отображаться пользователю строчный текст, выходящий за границы блока.
- CSS свойство white-space указывает, как будут отображены пробелы внутри элемента.
- CSS свойство word-break указывает перенос строки.
Другие свойства для тега :
- CSS свойство text-shadow добавляет тень к тексту.
- CSS свойство text-align-last выравнивает последнюю строку текста.
- CSS свойство line-height устанавливает межстрочный интервал.
- CSS свойство letter-spacing устанавливает расстояние между буквами/символами в тексте.
- CSS свойство word-spacing устанавливает расстояние между словами в тексте.
Изменение фона label с помощью hover
Изменение фона ссылки с помощью псевдокласса :hover
Необходимо сделать так, чтобы при наведение на одну любую из ссылок, ее фон менял цвет на прозрачно.
Изменение стилей элементов с помощью hover
Доброй ночи. Есть следующий блок: <div > <div > .
Изменение стилей элемента с помощью псевдокласса hover
Здравствуйте. Нужно сделать такой эффект при наведении, как на картинке, без использования.
Изменение фона label’a при нажатии
Ребята помогите с приложением Cуть проблемы: у меня на форме располагаются 4 label’a, мне нужно по.
Вопрос прост, описание не очень
У вас есть три radio с label. Во все label вложены разные картинки.
Вы хотите эти картинки сделать через background-image?
Что должно происходить после того, как маркер покидает конкретный radio?
Что должно происходить, когда конкретный radio получает маркер?
А то от family голова идет кругом.
просто прописать например для конкретного input + label по id картинку при такой структуре кода
инпут не чекнутый не дисэйбл не ховер и т.д. просто инпут а там я дальше накалякаю
одним словом перенести img ту что я заключаю между тегов label в style.css под background-image для конкретного елемента
инпутов много но типажа три
когда disabled напишу один фон когда не disabled напишу другой
Сообщение было отмечено новый вася как решение
Решение
Когда вы убираете картинку из html, ширина label схлопывается. Для того, чтобы прописать background, надо label задать размеры:
#family3 + label{ width:100px; height:200px; background: url(img1.png) no-repeat; }
Добавлено через 7 минут
спс большое все работает
#family3 + label{ background: url(1.png) no-repeat; background-size: cover; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
input[type="radio"] { display:none; } label { display: inline; } #family1:hover { background-color: rgba(217, 200, 20, 0.5); } #family1:hover+label { background-color: rgba(217, 200, 20, 0.5); } #family1:checked:hover{ background-color: rgba(67, 255, 255, 0.5); } #family1:checked:hover+label { background-color: rgba(67, 255, 255, 0.5); } #family1 + label{ width: 50px; height: 50px; background: url(daddy1.png) no-repeat; background-size: cover; } #family1:not(:checked) + label{ width: 50px; display: inline-block; border-radius: 25px; color: #000; background-color: rgba(60,92,90,0.4); cursor: pointer; } #family1:checked + label { width: 50px; display: inline-block; border-radius: 25px; color: #000; background-color: rgba(67,255,255,0.5); cursor: pointer; } #family1:disabled + label { background-color: rgba(0,0,0,0.3); border-radius: 25px; color: #4A4A4A; pointer-events: none; } #family1:disabled, #family1:disabled+label { background-color: rgba(0, 0, 0, 0); background-image: url(done.png) ; background-size: cover; }
input name='Name1' type='radio' id='family1' value='О'> label for='family1'>/label>
How to style labels with CSS?
The labels are used to define or set captions for any element on the web. It conveys useful information to the user about any element or maybe any section of the website.
The labels should be designed that it adds up the semantic meaning to it. Here, we will learn to style labels with CSS.
Styling the labels
The labels can be styled with some basic CSS properties like background-color , color , padding , font-size , etc.
Example: Styling the labels with CSS
Here, we have added three level topics. It has been added with some semantic background color.
span < padding: 16px; height: 10px; width: 100px; margin: 2px; >.label-1 < background-color: green; >.label-2 < background-color: yellow; >.label-3 Study Topics
Easy Medium Difficult
Output
Here is the output of the above program.
Example: styling the labels with CSS
In the next example, we have taken the same example and changed the background-color on :hover . Also added box-shadow property to each label.
Conclusion
In this tutorial, we have learned to style labels with CSS. We can use basic CSS property to do so. Here, we have added examples to demonstrate it.