Change the color of selected text using CSS?

HTML тег

HTML тег используется для определения выпадающего списка, который появляется при нажатии мышью на элемент формы и позволяет пользователю выбрать один из вариантов.

Для определения доступных вариантов выбора используется тег , вложенный в тег .

По умолчанию первый пункт в списке отображается как выбранный. Для изменения предопределенного варианта используется атрибут selected .

Для объединения нескольких вариантов в одну группу используется тег . Содержимое тега выглядит как заголовок жирного начертания.

Внешний вид списка зависит от использования атрибута size , который устанавливает высоту списка. Ширина списка зависит от длины текста в теге . Ширину можно также задать с помощью CSS стилей.

Если необходимо отправлять данные на сервер, либо обращаться к списку через скрипты, то тег

Синтаксис

Содержимое элемента заключается между открывающим () тегами. Закрывающий тег обязателен

Пример

html> html> head> title>Заголовок окна веб-страницы title> head> body> form action="action_form.php" target="_top"> select> option value="books">Книги option> option value="html">HTML option> option value="css">CSS option> option value="php">PHP option> option value="js">JavaScript option> select> form> body> html>

Результат

Пример

html> html> head> title>Заголовок окна веб-страницы title> head> body> select> optgroup label="Книги"> option value="html">HTML option> option value="css">CSS option> optgroup> optgroup label="Сниппеты"> option value="git">Git option> option value="java">Java option> optgroup> select> body> html>

В этом примере мы использовали тег для сбора опций в группе.

Результат

Пример

html> html> head> title>Заголовок окна веб-страницы title> head> body> p>Аэропорт вылета: p> form action="action_form.php" target="_top"> input type = "text" list = "airports" name="airports"> datalist id = "airports"> option value = "Санкт-Петербург"> option value = "Краснодар"> option value = "Москва"> option value = "Новосибирск"> datalist> input type = "submit" value = "подтвердить"> form> body> html>

Результат

selectexample3

В этом примере мы использовали тег , так как нам необходимо отправить данные на сервер.

Атрибуты

Атрибуты Значение Описание
autofocus autofocus Определяет, что список должен получить фокус при загрузке страницы.
disabled disabled Указывает, что список не активен, то есть пользователь не сможет взаимодействовать с ним.
form form_id Определяет форму с которой связан элемент.
Не поддерживается в Firefox.
multiple multiple Указывает, что за один раз можно выбрать несколько вариантов. Способ выбора нескольких вариантов зависит от операционной системы: в Windows необходимо удерживать нажатой клавишу CTRL, в Mac — клавишу CMD.
name name Определяет имя для раскрывающегося списка. Оно может быть использовано для доступа к данным формы после ее отправки или для ссылки на элемент в JavaScript.
required required Указывает, что выбор значения является обязательным.
size number Указывает количество видимых вариантов в раскрывающимся списке. Если значение атрибута size больше 1, но меньше общего количества вариантов списка, то браузер автоматически добавит полосу прокрутки, чтобы указать, что есть еще варианты для просмотра.

Как добавить стиль к тегу ?

Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :

  • 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 устанавливает расстояние между словами в тексте.

Источник

How to change the color of selected text using CSS?

Styling text on a website is a crucial aspect of web design and development. For doing this, CSS (Cascading Style Sheets) is a powerful tool to have at your disposal. CSS is a versatile tool that allows to manipulate the appearance of text in various ways. One of the most sought-after techniques is the alteration of the color of selected text. In this article we will learn two techniques to change the color of the selected text using CSS.

::selection pseudo-element

The ::selection pseudo-element is a powerful feature that enables us to select and style text that is currently being highlighted by the user. To change the color of the selected text, we use the color property. For instance, if we want to make the selected text appear in a maroon, we will use the following CSS −

This will change the color of the selected text to red for the entire web page.

Example

Here is an example to change the color of selected text to red and background color to black.

   ::selection 

Changing the color of selected text using CSS

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting

By using Specific elements or classes

We can change the color and background color of selected text on specific elements or classes. For example, we can change the color of selected text within a specific «h1» tag by using the following CSS −

This will change the color of selected text within the h1 element to white, and the background color of selected text to red.

Example

Here is an example to change the color of selected text to white and background color to red, text to red, background to yellow and

text blue and background to pink.

  h1::selection < background: red; color: white; >h2::selection < background: yellow; color: red; >p::selection 

Welcome to tutorialsPoint

Change the color of selected text using CSS

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting

Conclusion

Changing the color of selected text using CSS is a straightforward task that can be accomplished by utilizing the ::selection pseudo-element. By using the color and background-color properties, we can alter the appearance of selected text on website. Furthermore, we can use the ::selection pseudo-element on specific elements or classes for more precise control over the styling of selected text.

Источник

Overriding The Default Text Selection Color With CSS

text-selection-color.png

One of those cool CSS3 declarations that you can use today is ::selection , which overrides your browser-level or system-level text highlight color with a color of your choosing. At the time of this writing, only Safari and Firefox are supporting this, and both in slightly different ways. Fortunately, this can be thought of as one of those “forward-enhancement” techniques. It’s a nice touch for those using modern browsers, but it just gets ignored in other browsers and it’s not a big deal. Here is the rub:

Within the selection selector, color and background are the only properties that work. What you can do for some extra flair, is change the selection color for different paragraphs or different sections of the page. View Demo All I did was use different selection color for paragraphs with different classes:

p.red::selection < background: #ffb7b7; >p.red::-moz-selection < background: #ffb7b7; >p.blue::selection < background: #a8d1ff; >p.blue::-moz-selection < background: #a8d1ff; >p.yellow::selection < background: #fff2a8; >p.yellow::-moz-selection

Note how the selectors are not combined, even though the style block is doing the same thing. It doesn’t work if you combine them:

/* Combining like this WILL NOT WORK */ p.yellow::selection, p.yellow::-moz-selection

That’s because browsers ignore the entire selector if there is a part of it they don’t understand or is invalid. There is some exceptions to this (IE 7?) but not in relation to these selectors. For even more crazy flair, you could reveal an image with text selection.

Источник

Читайте также:  Что такое prototype javascript
Оцените статью