Css изменить содержимое элемента

content¶

Свойство content позволяет вставлять генерируемое содержание в текст веб-страницы, которое первоначально в тексте отсутствует.

Применяется совместно с псевдоэлементами ::after и ::before , они соответственно указывают отображать новое содержимое после или до элемента, к которому добавляются.

Демо¶

Синтаксис¶

 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
/* Keywords that cannot be combined with other values */ content: normal; content: none; /* values */ content: url('http://www.example.com/test.png'); content: linear-gradient(#e66465, #9198e5); content: image-set('image1x.png' 1x, 'image2x.png' 2x); /* alt text for generated content, added in the Level 3 specification */ content: url('http://www.example.com/test.png') / 'This is the alt text'; /* value */ content: 'prefix'; /* list of content values */ content: 'prefix' url('http://www.example.com/test.png'); content: 'prefix' url('http://www.example.com/test.png') 'suffix' / 'This is some alt text'; /* values, optionally with */ content: counter(chapter_counter); content: counter(chapter_counter, upper-roman); content: counters(section_counter, '.'); content: counters( section_counter, '.', decimal-leading-zero ); /* attr() value linked to the HTML attribute value */ content: attr(value string); /* Language- and position-dependent keywords */ content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote; /* Except for normal and none, several values can be used simultaneously */ content: open-quote counter(chapter_counter); /* Global values */ content: inherit; content: initial; content: revert; content: revert-layer; content: unset; 

Значения¶

<строка>Текст, который добавляется на веб-страницу, строка при этом должна браться в двойные или одинарные кавычки. Допускается использовать юникод для вставки спецсимволов. Спецсимволы HTML которые начинаются с амперсанда ( &sect ; например), будут отображаться как есть, т. е. простым текстом ( &sect ;, а не § ). attr() Возвращает строку, которая является значением атрибута тега указанного в скобках. Например, a::after добавит после ссылки её адрес, т. е. значение атрибута href . Если указанного атрибута нет, то вернётся пустая строка. open-quote Вставляет открывающую кавычку, тип которой устанавливается с помощью стилевого свойства quotes . close-quote Вставляет закрывающую кавычку. no-open-quote Отменяет добавление открывающей кавычки. no-close-quote Отменяет добавление закрывающей кавычки. url Абсолютный или относительный адрес вставляемого объекта. Если указанный файл браузер не может отобразить, то значение игнорируется. counter Выводит значение счётчика, заданного свойством counter-reset . none Не добавляет никакого содержимого. normal Задаётся как none для псевдоэлементов ::before и ::after .

Читайте также:  Python dict узнать размер

Применяется к псевдоэлементам ::before и ::after

Спецификации¶

Источник

Change Content in CSS

Change Content in CSS

  1. Use the :after Pseudo-Element and the display Property to Replace Text in CSS
  2. Use the :before Pseudo-Element and the visibility Property to Replace Text in CSS

The tutorial will introduce a few ways to change or replace the content in CSS.

Use the :after Pseudo-Element and the display Property to Replace Text in CSS

We can use the pseudo-elements in CSS to change or replace the contents written in HTML. Then use the :after pseudo-element and the content property to achieve our goal.

Use the :after selector to append some content after the selected content. To add the content, we use the content property.

We can write the desired content as the value of the content property. To replace or change the content, we can hide the previously written content and use the content property, selecting the element with the :after selector.

This method sets the display property to none to hide the previous text.

For example, create a div with the class text . Inside the div , write a span tag and the original text inside the span .

In CSS, select the span and set its display property to none . Next, use the :after selector to select the text class.

Finally, write the content property and set its value to the changed text in the body.

When the code snippet in the example below is run, the changed text is shown. Here, the text the original text is removed from the document, and it acts like the element does not exist.

This is because the value of the content property will take its space. As a result, the new content will be shown.

div class="text"> span>the original textspan>  div> 
.text span   display: none; > .text:after   content: 'the changed text'; > 

Use the :before Pseudo-Element and the visibility Property to Replace Text in CSS

We can change the content written in HTML using the :before pseudo-element in CSS. The :before pseudo-element works similarly to the :after pseudo-element, but the content is presented here.

Use it to write the content before the selected element. This method uses the content property as in the first method.

In addition, we can use the visibility property to hide the previous content and set it to hidden .

When set to hidden , the visibility property will make the content invisible, but the blank space will be shown in the document. But, using the :before selector will override the space with the new content.

For example, select the span element and set its visibility property to hidden in the example used in the first method.

But, remember to remove the previously applied styles. Next, select the text class with the :before selector and write the new content as in the example below.

Use display:none to hide the previous content. However, we cannot use visibility:hidden while using the :after selector as the hidden element’s space will be preserved.

div class="text"> span>beforespan>  div> 
.text span   visibility:hidden; > .text:before   content: 'after'; > 

Источник

content

Вычисляется none для псевдоэлементов ::before и ::after .

Любое количество текстовых символов. Нелатинские символы должны быть закодированы с использованием их escape-последовательности Unicode: например, \000A9 представляет собой символ авторского права.

URL-адрес, указывающий на внешний ресурс (к примеру, изображение). Если ресурс не может быть отображён, он игнорируется или отображается значение по умолчанию.

(en-US), указанный типом данных () или (en-US), или частью веб-страницы, определяемой функцией element() (en-US), указывающей содержимое для обозначения.

Значение CSS счётчика, как правило число. Его можно отобразить с помощью функций counter() (en-US) или counters() (en-US).Функция counter() имеет две формы записи: ‘counter(имя)’ или ‘counter(имя, стиль)’. Сгенерированный текст — это значение самого вложенного счётчика с заданным именем в области видимости данного элемента. Он отформатирован в указанном стиле (по умолчанию decimal ).Функция counters() также имеет две формы записи: ‘counters(name, string)’ или ‘counters(name, string, style)’. Сгенерированный текст — это значение всех счётчиков с заданным именем в области видимости данного элемента, от крайнего к вложенному. разделённых указанной строкой. Счётчики отображаются в указанном стиле (по умолчанию decimal ).

Значение атрибута x элемента в виде строки. Если атрибут x отсутствует, вернётся пустая строка. Чувствительность к регистру в названии атрибута зависит от языка документа.

Эти значения заменяются соответствующей строкой из свойства quotes (en-US).

Не вводит никакого содержимого, но увеличивает (уменьшает) уровень вложенности для кавычек.

Синтаксис

content =
normal | (en-US)
none | (en-US)
[ (en-US) | (en-US) ] (en-US) [ (en-US) / [ (en-US) (en-US) | (en-US) ] (en-US) + (en-US) ] (en-US) ? (en-US) | (en-US)
element( )

=

=
[ (en-US) (en-US) | (en-US) contents | (en-US) | (en-US) | (en-US) | (en-US) | (en-US) ] (en-US) + (en-US)

=
| (en-US)

=
| (en-US)
(en-US)

=
open-quote | (en-US)
close-quote | (en-US)
no-open-quote | (en-US)
no-close-quote

=
| (en-US)
| (en-US)

=
leader( )

=
counter( , ? (en-US) )

=
counters( , (en-US) , ? (en-US) )

=
url( (en-US) * (en-US) ) | (en-US)
src( (en-US) * (en-US) )

=
target-counter( [ (en-US) (en-US) | (en-US) ] (en-US) , , ? (en-US) )

=
target-counters( [ (en-US) (en-US) | (en-US) ] (en-US) , , (en-US) , ? (en-US) )

=
target-text( [ (en-US) (en-US) | (en-US) ] (en-US) , [ (en-US) content | (en-US) before | (en-US) after | (en-US) first-letter ] (en-US) ? (en-US) )

=
dotted | (en-US)
solid | (en-US)
space | (en-US)
(en-US)

=
| (en-US)

=
symbols( ? (en-US) [ (en-US) (en-US) | (en-US) ] (en-US) + (en-US) )

=
cyclic | (en-US)
numeric | (en-US)
alphabetic | (en-US)
symbolic | (en-US)
fixed

Примеры

Заголовки и двойные кавычки

В этом примере вставляются кавычки вокруг кавычек а добавляет слово «Глава» перед заголовками.

HTML

h1>5h1> p>According to Sir Tim Berners-Lee, q cite="http://www.w3.org/People/Berners-Lee/FAQ.html#Internet">I was lucky enough to invent the Web at the time when the Internet already existed - and had for a decade and a half.q> We must understand that there is nothing fundamentally wrong with building on the contributions of others. p> h1>6h1> p>According to the Mozilla Manifesto, q cite="http://www.mozilla.org/en-US/about/manifesto/">Individuals must have the ability to shape the Internet and their own experiences on the Internet.q> Therefore, we can infer that contributing to the open web can protect our own individual experiences on it. p> 

CSS

q  color: blue; > q::before  content: open-quote; > q::after  content: close-quote; > h1::before  content: "Chapter "; /* Пробел в конце создаёт разделение между добавленным контентом и остальным контентом*/ > 

Результат

Изображение в сочетании с текстом

В этом примере вставляется изображение перед ссылкой. Если изображение не найдено, вставляет текст.

HTML

a href="http://www.mozilla.org/en-US/">Mozilla Home Pagea> 

CSS

a::before  content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") " MOZILLA: "; font: x-small Arial, sans-serif; color: gray; > 

Результат

Целевые классы

В этом примере вставляется дополнительный текст после указанных элементов списка.

HTML

h2>Paperback Best Sellersh2> ol> li>Political Thrillerli> li class="new-entry">Halloween Storiesli> li>My Biographyli> li class="new-entry">Vampire Romanceli> ol> 

CSS

.new-entry::after  content: " New!"; /* Начальный пробел создаёт разделение между добавленным контентом и остальным контентом */ color: red; > 

Результат

Атрибуты изображений и элементов

В этом примере вставляется изображение перед каждой ссылкой и добавляет id атрибут после.

HTML

ul> li>a id="moz" href="http://www.mozilla.org/"> Mozilla Home Pagea>li> li>a id="mdn" href="https://developer.mozilla.org/"> Mozilla Developer Networka>li> ul> 

CSS

a  text-decoration: none; border-bottom: 3px dotted navy; > a::after  content: " (" attr(id) ")"; > #moz::before  content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") ; > #mdn::before  content: url("mdn-favicon16.png") ; > li  margin: 1em; > 

Результат

Замена элемента

В этом примере содержимое элемента заменяется изображением. Вы можете заменить содержимое элемента либо значением или изменить значение . Содержимое, добавленное с помощью ::before или ::after не будет сгенерировано, поскольку содержимое элемента будет заменено.

HTML

CSS

#replaced  content: url("mdn.svg"); > #replaced::after  /* не будет отображаться, если замена элемента поддерживается */ content: " (" attr(id) ")"; > 

Результат

Проблемы доступности

Сгенерированный CSS контент не включён в DOM. Из-за этого он не будет представлен в accessibility tree и некоторые комбинации вспомогательных технологий/браузеров не будут его объявлять. Если контент содержит информацию, которая имеет решающее значение для понимания цели страницы, лучше включить её в основной документ.

Спецификации

Поддержка браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 15 дек. 2022 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью