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.
content
Свойство, с помощью которого можно добавить на страницу то, чего нет в HTML-разметке.
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
Когда задано свойство content , то элемент заменяется на значение этого свойства. В качестве значения могут быть переданы различные типы: изображение, градиент или текст.
Пример
Скопировать ссылку «Пример» Скопировано
a::after content: "👉"; margin-right: 5px;>
a::after content: "👉"; margin-right: 5px; >
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Изображение в качестве содержимого. Может применяться к любому элементу.
div content: url("http://www.example.com/test.png");>
div content: url("http://www.example.com/test.png"); >
Все значения ниже могут применяться ТОЛЬКО к псевдоэлементам : : before и : : after .
div::before content: "prefix";>
div::before content: "prefix"; >
Значения счётчиков с использованием функций counter ( ) и counters ( ) :
div::before content: counter(chapter_counter);> div::before content: counters(section_counter, ".");>
div::before content: counter(chapter_counter); > div::before content: counters(section_counter, "."); >
Значения HTML-атрибутов с использованием функции attr ( ) :
div::before content: attr(value string);>
div::before content: attr(value string); >
Ключевые слова, зависящие от языка страницы и положения в тексте:
div::before content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote;>
div::before content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote; >
Использование нескольких значений одновременно. Исключение — ключевые слова normal и none :
div::before content: open-quote counter(chapter_counter);>
div::before content: open-quote counter(chapter_counter); >
Ключевые слова, которые нельзя комбинировать с другими значениями:
div::before content: normal; content: none;>
div::before content: normal; content: none; >
Как понять
Скопировать ссылку «Как понять» Скопировано
Чаще всего свойство content применяется к псевдоэлементам : : before и : : after . В зависимости от значения свойства псевдоэлемент принимает тот или иной вид:
- Если значением является просто строка, то она подставляется на место псевдоэлемента. Как правило, это до или после текстового содержимого тега.
- Есть несколько зарезервированных слов, которые также можно указывать в качестве значения. Используются они как совместно со свойством quotes , так и в автоматическом режиме:
- open — quote обозначает открывающую кавычку цитаты для текущего языка. Например, для русского это будет открывающая «ёлочка» ( « );
- close — quote обозначает закрывающую кавычку цитаты для текущего языка. Например, для русского это будет закрывающая «ёлочка» ( » );
Вспомните, как говорили мушкетёры:
Один за всех, все за одного!
blockquote> Вспомните, как говорили мушкетёры: q>Один за всех, все за одного!q> blockquote>
blockquote quotes: "«" "»" "„" "”";> blockquote::before content: open-quote;> blockquote::after content: close-quote;>
blockquote quotes: "«" "»" "„" "”"; > blockquote::before content: open-quote; > blockquote::after content: close-quote; >
«Вспомните, как говорили мушкетёры: „Один за всех, все за одного!”»
- no — open — quote и no — close — quote используются, когда не нужно отображать кавычки, но при этом продолжать увеличивать уровень вложенности;
- Если значением является результат выполнения функций counter ( ) или counters ( ) , то псевдоэлемент будет содержать вычисленное значение счётчика в текущий момент. Эти функции работают совместно со свойствами counter — reset и counter — increment ;
- Очень интересным значением является результат выполнения функции attr ( ) .
С помощью неё можно вывести в псевдоэлемент значение любого атрибута тега:
Ваш рейтинг: 212
p> Ваш рейтинг: span data-tip="Вычисляется на основе активности">212span> p>
[data-tip] position: relative; cursor: help;> [data-tip]:hover::after opacity: 1; visibility: visible;> [data-tip]::after content: attr(data-tip); position: absolute; top: 140%; left: 50%; transform: translateX(-50%); opacity: 0; visibility: hidden;>
[data-tip] position: relative; cursor: help; > [data-tip]:hover::after opacity: 1; visibility: visible; > [data-tip]::after content: attr(data-tip); position: absolute; top: 140%; left: 50%; transform: translateX(-50%); opacity: 0; visibility: hidden; >
🛠 . или красиво оформить нумерованный перечень
.benefits counter-reset: benefits;> .benefits-item counter-increment: benefits;> .benefits-item::before content: counter(benefits); position: absolute; font-size: 190px; font-weight: bold; left: 0; top: -0.35em; opacity: 0.5; color: #1A5AD7;>
.benefits counter-reset: benefits; > .benefits-item counter-increment: benefits; > .benefits-item::before content: counter(benefits); position: absolute; font-size: 190px; font-weight: bold; left: 0; top: -0.35em; opacity: 0.5; color: #1A5AD7; >