Цвет ссылок

Как установить цвет посещённой ссылки?

Как только пользователь открывает документ, на который указывает ссылка, она помечается как посещённая и меняет свой цвет на фиолетовый, установленный по умолчанию. Чтобы задать вид оформления посещенных ссылок, используйте псевдокласс :visited , который добавляется к селектору A , как показано в примере 1.

Пример 1. Цвет посещенных ссылок

HTML5 CSS 2.1 IE Cr Op Sa Fx

       

Посещённой ссылка становится после того, как на неё щёлкнули и перешли по ней на новую страницу.

Результат данного примера показан ни рис. 1.

Цвет посещённой ссылки

Рис. 1. Цвет посещённой ссылки

В примере рядовая текстовая ссылка имеет красный цвет, а посещённая — оливковый.

HTML по теме

CSS по теме

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Популярные рецепты

  • Как добавить картинку на веб-страницу?
  • Как добавить иконку сайта в адресную строку браузера?
  • Как добавить фоновый рисунок на веб-страницу?
  • Как сделать обтекание картинки текстом?
  • Как растянуть фон на всю ширину окна?
  • Как выровнять фотографию по центру веб-страницы?
  • Как разместить элементы списка горизонтально?
  • Как убрать подчеркивание у ссылок?
  • Как убрать маркеры в маркированном списке?
  • Как изменить расстояние между строками текста?
  • Как сделать, чтобы картинка менялась при наведении на нее курсора мыши?
  • Как открыть ссылку в новом окне?

Источник

With CSS, links can be styled in many different ways.

Links can be styled with any CSS property (e.g. color , font-family , background , etc.).

Example

In addition, links can be styled differently depending on what state they are in.

The four links states are:

  • a:link — a normal, unvisited link
  • a:visited — a link the user has visited
  • a:hover — a link when the user mouses over it
  • a:active — a link the moment it is clicked

Example

/* unvisited link */
a:link color: red;
>

/* visited link */
a:visited color: green;
>

/* mouse over link */
a:hover color: hotpink;
>

/* selected link */
a:active color: blue;
>

When setting the style for several link states, there are some order rules:

Text Decoration

The text-decoration property is mostly used to remove underlines from links:

Example

a:visited text-decoration: none;
>

a:hover text-decoration: underline;
>

a:active text-decoration: underline;
>

Background Color

The background-color property can be used to specify a background color for links:

Example

a:link <
background-color: yellow;
>

a:visited background-color: cyan;
>

a:hover background-color: lightgreen;
>

a:active background-color: hotpink;
>

This example demonstrates a more advanced example where we combine several CSS properties to display links as boxes/buttons:

Example

a:link, a:visited <
background-color: #f44336;
color: white;
padding: 14px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
>

a:hover, a:active background-color: red;
>

More Examples

Example

This example demonstrates how to add other styles to hyperlinks:

Example

Another example of how to create link boxes/buttons:

a:link, a:visited <
background-color: white;
color: black;
border: 2px solid green;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
>

a:hover, a:active background-color: green;
color: white;
>

Example

This example demonstrates the different types of cursors (can be useful for links):

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

:visited

The :visited CSS pseudo-class applies once the link has been visited by the user. For privacy reasons, the styles that can be modified using this selector are very limited. The :visited pseudo-class applies only and elements that have an href attribute.

Try it

Styles defined by the :visited and unvisited :link pseudo-classes can be overridden by any subsequent user-action pseudo-classes ( :hover or :active ) that have at least equal specificity. To style links appropriately, put the :visited rule after the :link rule but before the :hover and :active rules, as defined by the LVHA-order: :link — :visited — :hover — :active . The :visited pseudo-class and :link pseudo-class are mutually exclusive.

Privacy restrictions

For privacy reasons, browsers strictly limit which styles you can apply using this pseudo-class, and how they can be used:

  • Allowable CSS properties are color , background-color , border-color , border-bottom-color , border-left-color , border-right-color , border-top-color , column-rule-color , outline-color , text-decoration-color , and text-emphasis-color .
  • Allowable SVG attributes are fill and stroke .
  • The alpha component of the allowed styles will be ignored. The alpha component of the element’s non- :visited state will be used instead. In Firefox when the alpha component is 0 , the style set in :visited will be ignored entirely.
  • Although these styles can change the appearance of colors to the end user, the window.getComputedStyle method will lie and always return the value of the non- :visited color.
  • The element is never matched by :visited .

Note: For more information on these limitations and the reasons behind them, see Privacy and the :visited selector.

Syntax

Examples

Properties that would otherwise have no color or be transparent cannot be modified with :visited . Of the properties that can be set with this pseudo-class, your browser probably has a default value for color and column-rule-color only. Thus, if you want to modify the other properties, you’ll need to give them a base value outside the :visited selector.

HTML

a href="#test-visited-link">Have you visited this link yet?a>br /> a href="">You've already visited this link.a> 

CSS

a  /* Specify non-transparent defaults to certain properties, allowing them to be styled with the :visited state */ background-color: white; border: 1px solid white; > a:visited  background-color: yellow; border-color: hotpink; color: hotpink; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Цвет ссылок

С помощью HTML можно задавать цвета всех ссылок на странице, а также изменять цвета для отдельных ссылок.

Задание цвета всех ссылок на странице

Цвета ссылок задаются в качестве атрибутов тега . Атрибуты являются необязательными и если они не указаны используются значения по умолчанию.

link — определяет цвет ссылок на веб-странице (цвет по умолчанию синий, #0000FF).

alink — цвет активной ссылки. Цвет ссылки меняется при нажатии на ней кнопки мыши. Цвет по умолчанию красный, #FF0000.

vlink — цвет уже посещенных ссылок. Цвет по умолчанию фиолетовый, #800080.

В HTML цвета задаются обычно цифрами в шестнадцатеричном коде, в виде #rrggbb , где r, g и b обозначают соответственно красную, зеленую и синюю составляющую. Для каждого цвета задается шестнадцатеричное значение от 00 до FF, что соответствует диапазону от 0 до 255 в десятичном исчислении. Затем эти значения объединяются в одно число, перед которым ставится символ # (пример 1).

Пример 1. Задание цветов ссылок

      

Содержание сайта

Цвет не обязательно задавать в шестнадцатеричном формате, можно использовать и ключевые слова. В данном примере цвет фона веб-страницы установлен черным, а цвет ссылок — красным.

Для изменения цвета ссылок удобнее использовать CSS. Чтобы установить цвет для всех ссылок на веб-странице применяются следующие псевдоклассы, которые добавляются к селектору A .

visited — Стиль для посещенной ссылки.

active — Стиль для активной ссылки. Активной ссылка становится при нажатии на нее.

hover — Стиль для ссылки при наведении на нее мышью.

В примере 2 показано, как изменить цвет ссылок на веб-странице с помощью стилей. Для этого воспользуемся стилевым свойством color , оно задает цвет определенного текста, в данном случае, ссылок.

Пример 2. Цвет ссылок, заданных через стили

       

Содержание сайта

Задание цвета отдельных ссылок на странице

Вышеописанный способ задания цветов работает для всех ссылок веб-страницы. Однако, иногда возникает необходимость одновременно использовать разные цвета. Светлые, например, для темных областей веб-страницы, а темные цвета — соответственно для светлых. Для этого также можно воспользоваться стилями.

Пример 3. Изменение цвета ссылки с помощью стилей

      

Содержание сайта

Интернет-маркетинг

Юзабилити

В данном примере приведены три разных способа задания цвета с помощью стилей.

Источник

Читайте также:  Байт код java команды
Оцените статью