- ::after
- Try it
- Syntax
- Examples
- Simple usage
- HTML
- CSS
- Result
- Decorative example
- HTML
- CSS
- Result
- Tooltips
- HTML
- CSS
- Result
- Accessibility concerns
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Using :before and :after CSS selector to insert HTML [duplicate]
- 1 Answer 1
- Популярно о псевдоэлементах :Before и :After
- Синтаксис и поддержка браузерами
- Пример использования псевдоэлементов
- Использование
- Стилизация псевдоэлементов
- Использование вместе с псевдоклассами
- Добавление transition-эффекта
- Немного вдохновения
::after
In CSS, ::after creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
Try it
Note: The pseudo-elements generated by ::before and ::after are contained by the element’s formatting box, and thus don’t apply to replaced elements such as , or to elements.
Syntax
Note: CSS introduced the ::after notation (with two colons) to distinguish pseudo-classes from pseudo-elements. For backward compatibility, browsers also accept :after , introduced earlier.
Examples
Simple usage
Let’s create two classes: one for boring paragraphs and one for exciting ones. We can use these classes to add pseudo-elements to the end of paragraphs.
HTML
p class="boring-text">Here is some plain old boring text.p> p>Here is some normal text that is neither boring nor exciting.p> p class="exciting-text">Contributing to MDN is easy and fun.p>
CSS
.exciting-text::after content: " ; color: green; > .boring-text::after content: " ; color: red; >
Result
Decorative example
We can style text or images in the content property almost any way we want.
HTML
span class="ribbon">Look at the orange box after this text. span>
CSS
.ribbon background-color: #5bc8f7; > .ribbon::after content: "This is a fancy orange box."; background-color: #ffba10; border-color: black; border-style: dotted; >
Result
Tooltips
This example uses ::after , in conjunction with the attr() CSS expression and a data-descr custom data attribute, to create tooltips. No JavaScript is required!
We can also support keyboard users with this technique, by adding a tabindex of 0 to make each span keyboard focusable, and using a CSS :focus selector. This shows how flexible ::before and ::after can be, though for the most accessible experience a semantic disclosure widget created in some other way (such as with details and summary elements) is likely to be more appropriate.
HTML
p> Here we have some span tabindex="0" data-descr="collection of words and punctuation"> text span> with a few span tabindex="0" data-descr="small popups that appear when hovering"> tooltipsspan >. p>
CSS
span[data-descr] position: relative; text-decoration: underline; color: #00f; cursor: help; > span[data-descr]:hover::after, span[data-descr]:focus::after content: attr(data-descr); position: absolute; left: 0; top: 24px; min-width: 200px; border: 1px #aaaaaa solid; border-radius: 10px; background-color: #ffffcc; padding: 12px; color: #000000; font-size: 14px; z-index: 1; >
Result
Accessibility concerns
Using an ::after pseudo-element to add content is discouraged, as it is not reliably accessible to screen readers.
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.
Using :before and :after CSS selector to insert HTML [duplicate]
I’m wondering if the following is possible. I know it doesn’t work, but maybe I’m not writing it in the correct syntax.
li.first div.se_bizImg:before< content: "6 Businesses Found
"; >
Note that this is not a duplicate. The other question asks specifically about
or line break, and the answers give solutions to that special case. It won’t help if you want to add header and span tags.
Yes, this should not be marked a duplicate. The other question asks about a specific tag. Also — the answers in this one are much more helpful and easier to find from the search engines.
Having a question closed as a duplicate is not ipso facto a bad thing. Your question is still highly upvoted and has a good answer, and it helps more people by being able to find answers. They may get the answer here, or the other may help more. Everybody wins.
@Tas: I agree with you just in that «Having a question closed as a duplicate is not ipso facto a bad thing». As far as linking the other question is concerned, just a mention of the so called «duplicate question» in a comment should be sufficient, but not closing this post as duplicate when it’s not.
1 Answer 1
content doesn’t support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is » inside a » block. You should mix ‘ and » ( class=’headingDetail’ ).
If content did support HTML you could end up in an infinite loop where content is added inside content .
@Foxinni the more significant reason for not allowing html inside the content parameter is the fact that CSS is designed to work in a single pass-through of the page. If there were html, that would need to be styled, which means the css would need to come back and process itself all over again to style that HTML after it was done styling everything else. This extra functionality would rarely be used by anyone but would still come with a speed cost to everyone.
I think the more fundamental reason for not allowing html in content is the huge security risks involved in that. Any site that allows custom CSS would be hugely open to XSS attacks.
Another possibility is to use the emerging standard web components instead of css. Then you could do something like that. w3.org/TR/components-intro/#defining-a-custom-element
I eventually found this question/answer because I was looking for a way to have custom list styles and still handle wrapping properly. This was my solution: a list using a div for the list-style, a div for the content, and flex.. Hopefully this helps someone some day.
Популярно о псевдоэлементах :Before и :After
Псевдоэлементы :before и :after позволяют добавлять содержимое (стили) до и после элемента, к которому были применены.
Всего существует несколько типов псевдоэлементов: :first-line, :first-letter, ::selection, :before и :after. В этой статье подробно рассмотрены последние два, как наиболее полезные.
Синтаксис и поддержка браузерами
Псевдоэлементы появились еще в CSS1, но пошли в релиз только в CSS2.1. В самом начале в синтаксисе использовалось одно двоеточие, но в CSS3 используется двойное двоеточие для отличия от псевдоклассов:
Но в любом случае, современные браузеры умеют понимать оба типа синтаксиса псевдоэлементов, кроме Internet Explorer 8, который воспринимает только одно двоеточие. Поэтому надежнее использовать одно.
Пример использования псевдоэлементов
:before Это основной контент. :after
Элементы :before и :after не будут сгенерированы, т.е. не будут видны в коде страницы, поэтому они и называются псевдоэлементами.
Использование
Использовать псевдоэлементы крайне просто: :before добавляется перед нужным элементом, а :after — после.
Для добавление контента внутри псевдоэлементов можно воспользоваться CSS-свойством content.
Простой пример: необходимо добавить кавычки для цитаты:
blockquote:before < content: open-quote; >blockquote:after
Стилизация псевдоэлементов
К псевдоэлементом можно применять такие же стили, как и к «реальным»: изменение цвета, добавление фона, регулировка размера шрифта, выравнивание текста и т.д.
blockquote:before < content: open-quote; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; background: #ddd; float: left; position: relative; top: 30px; >blockquote:after
Созданные элементы по умолчанию inline-элементы, поэтому при указании высоты или ширины необходимо установить display: block:
blockquote:before < content: open-quote; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; background: #ddd; float: left; position: relative; top: 30px; border-radius: 25px; /** define it as a block element **/ display: block; height: 25px; width: 25px; >blockquote:after < content: close-quote; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; background: #ddd; float: rightright; position: relative; bottombottom: 40px; border-radius: 25px; /** define it as a block element **/ display: block; height: 25px; width: 25px; >
Также внутри псевдоэлемента можно использовать картинку вместо обычного текста, и даже добавлять фоновое изображение.
blockquote:before < content: " "; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; float: left; position: relative; top: 30px; border-radius: 25px; background: url(images/quotationmark.png) -3px -3px #ddd; display: block; height: 25px; width: 25px; >blockquote:after < content: " "; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; float: rightright; position: relative; bottombottom: 40px; border-radius: 25px; background: url(images/quotationmark.png) -1px -32px #ddd; display: block; height: 25px; width: 25px; >
В этом примере свойство content содержит пустую строку, это необходимо, иначе псевдоэлемент не будет правильно отображаться.
Использование вместе с псевдоклассами
Псевдоэлементы могут быть использованы вместе с псевдоклассами, в нашем примере это поможет добавить hover-эффект кавычкам:
blockquote:hover:after, blockquote:hover:before
Добавление transition-эффекта
Также можно применить свойство transition для плавного изменения цвета кавычек:
transition: all 350ms; -o-transition: all 350ms; -moz-transition: all 350ms; -webkit-transition: all 350ms;
К сожалению, это нормально работает только в последних версиях Firefox.
Посмотреть демонстрацию примера из этой статьи.
Немного вдохновения
Три примера использования псевдоэлементов :before и :afte: