- Why is the pseudo content :after not shown after but in the corresponding div?
- 3 Answers 3
- [Fixed] CSS :after element is not working
- 🔔 Table of contents
- What is the :after element?
- 💡 Tip — whats the difference with ::after and :after ?
- Reason 1 — not providing the content property
- Reason 2 — not valid with the HTML tag
- Reason 3 — content property is not valid
- 💡 Tip — to combine strings in content , separate them with a whitespace
- Browser support and bugs
- Summary
- 👋 About the Author
- 👉 See Also 👈
- Почему :after не отображается?
- 2 ответа 2
- Похожие
- Подписаться на ленту
- Почему псевдоэлементы ::before и ::after не работают для полей ввода и картинок
Why is the pseudo content :after not shown after but in the corresponding div?
But the after content is placed inside the scroll bars. My expectation was that it comes actually after the scrollable area.
3 Answers 3
The :after content comes within the scrollable area because even though the element is named :after , it is in actual terms a child of the div.box and hence will be positioned within the .box element (that is within the scrollable area).
From MDN: The CSS ::after pseudo-element matches a virtual last child of the selected element.
So the code in question in essence becomes the same as the following snippet.
If you want it positioned outside the div.box then you would have to use the :after on a container (or) use absolute positioning.
@ceving: As far as I can remember, they are the same. The only reason why two colons were added was to distinguish pseudo-elements from pseudo-classes and pseudo-selectors
I think you’ve become a little confused with pseudo elements, so i’ll hopefully clear a few things up for you:
The ::after pseudo-element can be used to describe generated content after an element’s content.
A quick demonstration of this would be:
In CSS 2.1, it is not possible to refer to attribute values for other elements than the subject of the selector.
See how, no matter where the div is, the pseudo element will be displayed after the element it is attached to. This is the way pseudo elements were designed for -to add content before or add content after .
This means that the :after is positioned relatively to the ‘real’ element, and not appear after the ‘scrollbars’.
Instead, if you position your pseudo element absolutely, then as you would expect with positioning a child element, you can ‘move’ it using the left , right , top and bottom properties:
However, I would instead wrap the scrollable content in a div, and that way you would have much more control over the positioning of the element.
The similarities in ::after and :after
This [double-colon] notation is introduced … in order to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in CSS level 3. ~Spec
There is no difference between the two notations
The slightly Long answer is.
With the introduction of CSS3, in order to make a differentiation between pseudo-classes and pseudo-elements, in CSS3 all pseudo-elements must use the double-colon syntax ( ::after ), and all pseudo-classes must use the single-colon syntax ( :first-child ).
However, since IE8 and below doesn’t understand this ‘double colon’ syntax (amongst so many others), browsers will accept the single colon syntax anyway (allowing IE 8 and below to also understand it). This is why developers, on the broad side, have chosen to keep using the single colon syntax in order for IE8 (and below) to understand, giving your site better browser compatability.
Further Reading
[Fixed] CSS :after element is not working
A few ways to fix why :after element is not working. 1. We need to check if we are using the right HTML tags, 2. using the content property correctly and 3. Check the browser combatibility.
Apr 20, 2022 | Read time 8 minutes
🔔 Table of contents
When creating web designs or interfaces, we can use pseudo-elements to keep our HTML clean. Insteading of adding a heap of HTML tags and styling them, coming up with class names, etc we can just use pseudo elements such as :after .
What is the :after element?
The :after pseudo element combined with the content CSS property creates a child element inside a given element after its contents.
Alternatively the :before pseudo element (when combined with the content property) creates a child element before the element’s contents. If you are looking for fixing issues specifically for ::before check out my post here How to fix CSS before not working issues
To visualize this, consider the following paragraph HTML element with “Hello world” as its contents. We can see the layout of the HTML element with the :before and :after child elements expanded:
To add style to these pseudo elements, we need to use the content CSS property
💡 Tip — whats the difference with ::after and :after ?
Using ::after (two colons) vs :after (one colon) is just based on the version of CSS. CSS3 version uses the two colons ( :: ) since with this version it also introduced pseudo classes. Having two colons just distingishes from pseudo elements and pseudo classes. The CSS2 version uses one colon ( : ) — most browsers will support both versions.
Browsers such as IE8 do not support CSS3, so you will need to stick with the single colon (CSS2) syntax.
Reason 1 — not providing the content property
A common reason when using the :after pseudo elements is that your styles is not appearing. We need to delare content:»» property!
Lets say we have the following style — we want a red box inside the .my-element class.
This does not work because we dont have the content property specified. Now the content property does not need to have a value, according to the spec we just need to specify it - even if its a empty string:
Reason 2 — not valid with the HTML tag
One reason why :after pseudo elements is not working is that you are using replaced elements. So what the heck is a replaced element?
Additionally it wont work with
elements too.
Basically replaced elements will have all its contents replaced — so when rendered by the browser, we cannot see any :after or :before pseudo elements. Therefore the styling will not apply.
So if you are using :after for the above HTML tags, then most likely it will not work. For example, in the below, we want to add text after and before images. This will not work since is a replaced element!
More information can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element
Reason 3 — content property is not valid
Another common reason why the :after pseudo element is not working and picking up your styles is that you are using the content property incorrectly.
Keep in mind that the content property will not work on regular elements — it only applies to :after and :before
- a string value — content:»Blah» — string values and even emojis can be used!
- a empty string content:»»
- image urls — url(/path/to/image.jpg); — the image will be inserted at exact size and cannot be resized
- counter() function — content: counter(li)
- attr() function content:attr(data-value) — this will take the string value of the HTML attribute and renders it in the content section
💡 Tip — to combine strings in content , separate them with a whitespace
Lets say you are using multiple calls to the CSS function of attr() to build up your content value.
Unlike programming languages such as JavaScript, to concatenate the strings and values together, we just separate the with whitespace instead of + (plus) or . (dot).
Consider the following HTML, we want to have a :after pseudo element to display the data-name and data-age :
Browser support and bugs
- IE9, IE10, IE11 ignore CSS rem units in the line-height property
- Firefox & Edge do not support :after and :before for input fields
- Animation and transition support limited on IE, Safari and Safari Mobile. Chrome supports this as of version 26.
- IE8 only supports the single-colon CSS 2.1 syntax (i.e. :pseudo-class). It does not support the double-colon CSS3 syntax
Summary
In this article we went over a few reasons why the :after pseudo element does not work.
To troubleshoot, we can follow the below checklist:
- Check that we are providing the content CSS property when defining our :after element. The content property can even be a empty string, but it has to be there to enable the :after element and its styles to appear
- Verify that we are using the :after element on the right HTML tags. Replaced elements such as , , , ,
, , , and will not support :after and :before elements. This is because on render, their whole content will be replaced (including the psuedo elements)
- Check that we are using the content CSS property correctly — cannot use HTML tags, make sure it is a string input value, when combining strings and CSS functions such as attr() we can combine them with the space character instead of a + (plus)
- Determine browser support — IE uses single colon (CSS2) syntax instead of double colon (CSS3), animation and transition support is limited
👋 About the Author
G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.
My aim to share what I have learnt with you! (and to help me remember 😅)
👉 See Also 👈
Почему :after не отображается?
Скрипт создает элемент, модальное окно, Вывод работает. Окну прописаны такие стили:
.modal_wrapper < &:after < position: fixed; z-index: 2; height: 100%; width: 100%; background-color: rgba(0, 0, 0, 0.5); >.modal_accept < position: fixed; width: 480px; height: 192px; border-radius: 5px; box-shadow: 0px 0px 10px 0px rgba(50, 50, 50, 0.25); top: 35%; left: 50%; transform: translateX(-50%); background-color: white; z-index: 4; #accept < position: absolute; top: 40px; left: 50%; transform: translateX(-50%); >p < font-size: 20px; text-transform: uppercase; font-family: 'Roboto Slab', serif; display: block; width: 72.92%; position: absolute; bottom: 40px; left: 50%; transform: translateX(-50%); font-weight: 700; text-align: center; >a < position: absolute; right: 14px; top: 14px; >> >
Но элемент :after не появляется по какой-то причине, хотя в стилях прописано. В чем может быть проблема?
2 ответа 2
Вы не указали свойство content: » у after.
для псевдо элементов типа : after и :before обязательно наличие content:»»;
т.е в вашем случае должно быть так :
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.27.43548
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Почему псевдоэлементы ::before и ::after не работают для полей ввода и картинок
В CSS псевдоэлементы ::before и ::after нельзя добавлять к текстовым полям и изображениям, поскольку эти элементы, так называемые «замещаемые элементы», специальная категория объектов, описанная в разделе «Рендеринг» стандарта HTML:
Следующие элементы могут быть полностью заменены:
audio, canvas, embed, iframe, img, input, object, video.
Участник CSS Working Group под ником fantasai объясняет это на GitHub:
Замещаемые элементы могут полностью заменить все содержимое элемента, в том числе псевдоэлементы ::before и ::after. Вот почему в замещаемых элементах не работают псевдоэлементы.
Например, невозможно использовать ::before для элемента img, чтобы отобразить альтернативный текст (alt) — при этом метод сработает для других элементах (например на параграфе p).
/* This doesn’t work! */ img::before
В зависимости от браузера и других факторов, элемент img иногда может быть не замещаемым. Например, если изображение не загружается, у нас появляется возможность добавить ::before и ::after к img (эта возможность есть только в Chrome и Firefox).
Ситуация становится более запутанной, когда дело касается элементов формы. Элементы input и textarea, в настоящее время рассматривается как «частично замещенные» — определение, которое использует Tab Atkins (редактор спецификаций CSS) в обсуждениях Working Group на GitHub.
Так или иначе, возможность добавления ::before и ::after для полей ввода зависит от типа input и используемого браузера. Например, Chrome и Safari поддерживают свойство content для input type=»checkbox» и input type=»radio».
input::before < content: '💔'; line-height: 1; vertical-align: top; position: relative; left: -1.5em; >input:checked::before
Если у вас возникли проблемы с использованием ::before или ::after для какого либо элемента, не забудьте проверить, не является ли этот элемент полностью или частично замещаемым элементом.