- ::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
- Популярно о псевдоэлементах :Before и :After
- Синтаксис и поддержка браузерами
- Пример использования псевдоэлементов
- Использование
- Стилизация псевдоэлементов
- Использование вместе с псевдоклассами
- Добавление transition-эффекта
- Немного вдохновения
- Размер картинки в свойстве content
- Can You Apply a Width to a :Before/:After Pseudo-Element (Content:Url(Image))
- Can you apply a width to a :before/:after pseudo-element (content:url(image))?
- Can I change the height of an image in CSS :before/:after pseudo-elements?
- How to change the size of an image inserted with ::before or ::after peudo-element in CSS
- How can I set size of css-content-image?
- An object with fixed sizes inside :before or :after pseudo element
- width and height doesn’t seem to work on :before pseudo-element
- Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
::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.
Популярно о псевдоэлементах :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:
Размер картинки в свойстве content
Всем привет.
Мне нужно установить картинку через псевдо элемент:after. Пример находится здесь. Картинку вставил, но размеры не получается менять! Почему так?? Подскажите, пожалуйста. Спасибо!
Загрузка картинки для спрайта не из Content
Здравствуйте! Подскажите, пожалуйста, возможна ли загрузка картинки для спрайта не из Content, а.
Записываю в таблицу картинки из Img контрола, как узнать размер картинки?
Заполняю в цикле Img контейнер картинками из shape группы из эксела. Картинки могут быть реальными.
Размер картинки больше чем размер шапки
Всем привет!ребята,у меня размер картинки больше чем высота шапки.как мне сделать так чтобы.
Подогнать размер картинки под размер формы
Здравствуйте! Я накладываю изображение на форму, но я столкнулся с проблемой. Мой.
Eduardo_1992, вставляйте изображение не через content, а background, тогда его размеры можно менять. http://jsfiddle.net/vadim_Lasso/Lnswoc8f/18/
div:after { background-image: url([url]https://lh6.ggpht.com/D0gDo9tdSqVM8oel0-mRBNsLF1Gsol4vAd8dD72trSXvzOT2h5BlAVNLvRkI1bCaik0=w300);[/url] background-size: 10px 10px; width: 10px; height: 10px; display: block; content: ""; position: absolute; top: 3px; right: 3px; }
Can You Apply a Width to a :Before/:After Pseudo-Element (Content:Url(Image))
Can you apply a width to a :before/:after pseudo-element (content:url(image))?
You’re not crazy: it is indeed not possible to change the dimensions of an image that is inserted using content , whether it’s inserted with url() , image() , image-set() , element() , or a CSS gradient. The image is always rendered as is. This is known as replaced content, or a replaced element (except we’re not talking about elements here).
However, since replaced elements can be resized using width and height as described in section 10 of the CSS2.1 spec, this raises the question of why the properties don’t seem to apply here. The answer to this, it would seem, is that the properties do apply, but to the pseudo-element box instead — you can see this by giving your pseudo-element a background color. Rather than replacing the pseudo-element box itself, the image is rendered as a child of the pseudo-element box, and therefore cannot be styled at all (as it would require another pseudo-element which doesn’t exist).
And that lends itself to another question: why doesn’t it replace the pseudo-element box altogether? Unfortunately, CSS2.1 does not specify this behavior at all, so the implementation that was agreed on is to render the content as a child of the pseudo-element box instead:
CSS2.1 doesn’t really clearly define the processing model of ‘content’ on ::before and ::after, but the informative examples in CSS 2.1, the fact that ‘content’ specifies a list of things, and the desire for consistency has led to UA behavior being the following: the ‘content’ property specifies a list of things that become children of the ::before or ::after box.
-Boris
Hopefully this will be further addressed in CSS Generated Content level 3, on which rewriting work has just begun.
In the meantime, if you want to be able to resize the :after pseudo-element and the image that’s generated, you will need to apply it as a background image instead and — assuming browser support isn’t an issue — use background-size along with width and height to scale it (based on the understanding that those properties apply to the pseudo-element box instead).
Can I change the height of an image in CSS :before/:after pseudo-elements?
Adjusting the background-size is permitted. You still need to specify width and height of the block, however.
.pdflink:after background-image: url('/images/pdf.png');
background-size: 10px 20px;
display: inline-block;
width: 10px;
height: 20px;
content:"";
>
See the full Compatibility Table at the MDN.
How to change the size of an image inserted with ::before or ::after peudo-element in CSS
Hi why dont you add your image as a background image and add the following
.smile::before content: ' ';
background-image: url(../../../../Pictures/Smilie.jpg);
background-size:contain;
height: 100px;
width: 100px;
>
How can I set size of css-content-image?
also, you could set the content to empty string and use a background image. Just alternatively.
.upper-menu .search-form::after content: ' ';
display: inline-block;
position: absolute;
background: #bada55 url("img_2x.png") no-repeat;
background-size: contain;
height: 10px;
width: 10px;
top: 5px;
right: 22px;
>
An object with fixed sizes inside :before or :after pseudo element
From my answer to this related question:
In the meantime, if you want to be able to resize the :after pseudo-element and the image that’s generated, you will need to apply it as a background image instead and — assuming browser support isn’t an issue — use background-size along with width and height to scale it (based on the understanding that those properties apply to the pseudo-element box instead).
background-image: url("../images/img.png");
background-size: cover;
(or the shorthand, background: url(«../images/img.png») 0 0 / cover )
As for scaling your pseudo-element proportionally, I think you should be able to accomplish this using the padding-bottom trick. For an image with a ratio of 1:2, padding-bottom: 200% seems to work in this example:
.container < border: thick solid; margin: 1em;>
.large.container < width: 100px; >.small.container < width: 50px; >
.container::after < content: ''; display: block; background: url(http://placehold.it/100x200) 0 0 / cover; padding-bottom: 200%;>
width and height doesn’t seem to work on :before pseudo-element
Note: The ::before and ::after pseudo-elements are actually laid display: inline; by default.
Change the display value to inline-block for the width & height to take effect while maintaining inline formatting context.
a.infolink::before content: '?';
display: inline-block;
background: blue;
color: white;
width: 20px;
height: 20px;
>
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
$('span').hover(function() $(this).attr('data-content','bar');
>);
span:after content: attr(data-content) ' any other text you may want';
>
If you want to prevent the ‘other text’ from showing up, you could combine this with seucolega’s solution like this:
$('span').hover(function() $(this).addClass('change').attr('data-content','bar');
>);
span.change:after content: attr(data-content) ' any other text you may want';
>