Css content with html tags

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.

Источник

CSS Content

CSS has a property called content. It can only be used with the pseudo-elements ::after and ::before. It is written like a pseudo selector (with the colon), but it’s called a pseudo-element because it’s not actually selecting anything that exists on the page but adding something new to the page. This is what it looks like:

And the output would be like: • Email address: [email protected] Maybe that example doesn’t get you drooling, but pseudo-element content can be quite useful and do cool things. Let’s go through some ideas and considerations.

Hey! That’s content not design!

The first concern might be that of a separation-between-content-and-design purist. You are literally adding text content to the page with CSS content, and that breaks that barrier. The spec is done and the idea implemented, but that doesn’t mean it’s not worth discussing. If you have an opinion about CSS content and its use, please share in the comments. I think it’s awesome and perfectly suited for CSS. Consider the example above where we preface all elements with a class of email-address with the text “Email address: “. That is a design decision, where for the clarity of content, it was decided that having that text before email addresses made the content more clear. Perhaps in a redesign of the site, there was less room where those email addresses are being displayed and it was decided that instead of prefacing them with text, a small icon would be used instead. This fits with the idea of CSS, in that the HTML content doesn’t need to change at all, this change could be solely accomplished with CSS. I’m going to publish an article tomorrow with this kind of idea.

If you need to use a special character in the CSS content, it’s kinda weird. How I do it is I figure out what the ASCII number is for the symbol. This chart of glyphs is handy. So on that chart the copyright © symbol is © – so the ASCII number is 169. Then I drop that number in the Entity Conversion Calculator which will convert it into what you need for CSS. Here’s some random useful ones: \2018 – Left Single Smart Quote
\2019 – Right Single Smart Quote
\00A9 – Copyright
\2713 – Checkmark
\2192 – Right arrow
\2190 – Left arrow

Example Trick: Checkmark visited links

#main-content a:visited::before

You are able to insert attributes of the elements you are targeting as content. For example, an anchor link might have a title attribute:

Any attribute can be targeted as such, in the format attr(name-of-attribute). If you’d like to insert something into the HTML to use for a CSS content purpose (but nothing else), you could use the new data- attribute prefix in HTML5.

Example Trick: CSS3 tooltips

a < color: #900; text-decoration: none; >a:hover < color: red; position: relative; >a[title]:hover::after

This example uses the title attribute, and other examples like this that you find around the web also use the title attribute. It’s probably the correct one to use. However, do note that browsers have their own tooltip popups that they do. When that comes up, it will cover this, and look weird. I tried to take a screenshot of the issue but there it wasn’t letting me for some reason. There is no way to suppress this, other than just not using the title attribute. HTML5 data- attributes, again, could be useful here.

  • Firebug can’t yet target pseduo elements. The web inspector in WebKit browsers can target them, but don’t show their property/values. I heard the IE dev tools could target them too, but not sure about the property/values.
  • In WebKit, they have to be block level to be rotated. Firefox can rotate inline elements/pseudo-elements.
  • In Firefox 3.0, pseudo elements can’t be absolutely positioned.
  • They cannot be transitioned or animated.

Example Trick: Fancy email link popouts

I had an idea I wanted to try where you would have a vertical list of names, and as you moused over them, their email addresses would slide out from underneath them. To have the HTML be as clean as possible, I thought it would be cool to use the an ::after pseudo-element and a -webkit-transition to make it happen. But, alas, you cannot animate or transition a pseudo-element.

Using the ::after /content method, I got an example working it just doesn’t slide out like I thought would be cool. Using s I got the idea working, also in the demo page.

Example trick: display full links in print stylesheets

Browser support / Accessibility

All the major browsers (Firefox 3+, Safari 3+, Chrome 3+, Opera 10+, and Internet Explorer 8+) (See the full chart) support CSS content with the ::after/::before pseudo-elements and the spec is in its full candidate recommendation status.

Regarding accessibility, I’m just not 100% sure what the situation was. I was trying to use VoiceOver with Safari on my Mac with the email popout links demo. For best accessibility, I would think the goal would be to get it to read the whole text, including the CSS content being added. I had trouble getting it to do that, but I thought I did get it to do it once somehow. I was really bad at using VoiceOver and found it frustrating to get it to do what I was trying to do even at the most basic levels. If someone knows more about accessibility as it relates to CSS content, I’m sure we’d all love to know more.

Источник

Читайте также:  Найти индексы всех вхождений подстроки python
Оцените статью