Css псевдоэлементы не работают

[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

Читайте также:  Javascript window open http

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:

  1. 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
  2. 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)
  3. 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)
  4. 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 👈

Источник

Почему псевдоэлементы ::before и ::after не работают для полей ввода и картинок

input 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 для какого либо элемента, не забудьте проверить, не является ли этот элемент полностью или частично замещаемым элементом.

Источник

doctor Brain

Псевдоэлементы CSS ::before и ::after могу быть неприменимы для полей ввода и изображений, так как HTML-элементы и являются замещаемыми элементами (replaced elements). Для таких элементов отведена целая категория в rendering section описания HTML-стандартов.

Следующие элементы могут быть замещаемыми: audio, canvas, embed, iframe, img, input, object, и video.

Fantasai — представитель рабочей группы CSS так же дает объяснения этой особенности замещаемых элементов на GitHub:

Замещаемые элементы заменяют весть контент элемента, в том числе содержимое псевдоэлементов ::before и ::after. Именно поэтому такие псевдоэлементы для замещаемых элементов работать не будут.

Например, невозможно отобразить альтернативный текст элемента с помощью ::before , хотя такой подход эффективен в отношении многих других HTML-элементов (в том числе

).

/* Такой пример работать не будет! */ img::before

Внимание: Элемент не всегда является замещаемым — это зависит от используемого в данный момент браузера и ряда других факторов. Например, если нет возможности загрузить изображение, псевдоэлементы ::before и ::after будут доступны к использованию в браузерах Chrome и Firefox.

Но и это не все. Когда заходит речь об использовании элементов формы, ситуация становится еще менее понятной. Так элементы и можно назвать частично замещаемыми (semi-replaced). Этот термин предложил Таб Аткинс — редактор спецификаций CSS в обсуждениях рабочей группы на Github:

Все типы полей ввода, как минимум “частично замещаемые”. Мы до сих пор не можем быть полностью уверены в том, как такое состояние работает. Но это не “замещаемые элементы” в их полном представлении, так как они имеют определенные неизменяемые внутренние размеры, которым подчиняются (в отличие от обычных элементов).

Возможность добавить контент к элементам формы с помощью CSS-псевдоэлементов ::before и ::after зависит как от типа самого элемента, так и от используемого браузера. Например, Chrome и Safari поддерживают содержимое псевдоэлементов ::before и ::after для чекбоксов и радиокнопок:

/* Такой пример будет работать в Chrome и Safari! */ input::before < content: '💔'; line-height: 1; vertical-align: top; position: relative; left: -1.5em; >input:checked::before

Итак, если у Вас возниакают проблемы с использованием контента псевдоэлементов ::before или ::after , не забывайте проверить, с каким элементом Вы работаете — возможно он являетмся замещаемым полностью или частично.

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

Источник

Почему у меня не работает :after/:before на img если прописан путь к картинки?

У меня вот такая ситуация получилась. Я только учу css еще, но раньше с :after/:before проблем не было, а сейчас у меня получилось так:

Я сверстал блок, расположил поверх img кнопку с помощью :before, и хотел еще добавить тень с помощью :after. Кнопку добавил, и сразу решил прописать ссылку на какой-то имедж-холдер, чтобы img не был пустым, и в этот момент моя кнопка, которая располагалась в левом-верхнем углу, пропала.

Я уже пробовал и с z-index’ом решим эту проблему, но никак.

Почему так получилось, и подскажите, пожалуйста, как это можно решить.

 
design-picture

Beautifully Coded

Not just superficial looks, Redux is beautiful behind the scenes too.

.feature < display: inline-block; padding: 7px 35px 21px 0; >.feature img < height: 55px; width: 55px; border-radius: 10px; position: relative; float: left; padding: 0 12px 5px 0; /*overflow: hidden;*/ left: 0; top: 0; >.feature img:before, .feature img:after < content: ''; position: absolute; display: block; >.feature img:before < height: 30px; width: 30px; background: url(../img/sprite.png) 59px 117px; left: -8px; top: -7px; >.feature img:after < left: 0; top: 0; border:1px solid red; >.details < float: left; width: 210px; margin-top: -7px; >.details h3 < font: bold 13px/20px 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #f1eee5; padding: 0 0 7px 0; margin: 0; width: 100%; >.details p < font: 12px/20px 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #979797; padding: 0; margin: 0; >

Источник

Почему не отображается псевдоэлемент befor?

5cbcdeab4bdea117097348.jpeg

Всем привет!
Есть три блока, у каждого сверху псевдоэлемент (отличаются только бэкграундом. )

Всем трем блокам прописал одинаковый код:

.item-ecommerce::before < content: ""; background: url(/img/Icon-Basket.png) no-repeat 15px; display: block; margin: auto; width: 70px; height: 70px; border: 4px solid #f2d048; border-radius: 50px; opacity: .8; >.item-web::before < content: ""; background: url(/img/Icon-Laptop.png) no-repeat 15px; display: block; margin: auto; width: 70px; height: 70px; border: 4px solid #f2d048; border-radius: 50px; opacity: .8; >.item-web::before < content: ""; background: url(/img/Icon-Locked.png) no-repeat 15px; display: block; margin: auto; width: 70px; height: 70px; border: 4px solid #f2d048; border-radius: 50px; opacity: .8; >

Проблема:
Проверяю в хроме — первый как влитой встал, второй почему то имеет стили своего before и третьего. Третий элемент вообще без before. В чем мой косяк? Код проверил, все ровно. Спасибо
5cbcdf28d83d4826469408.jpeg5cbcdf2f90ab9576654119.jpeg 5cbcdf35bd8ca073282567.jpeg

Источник

Оцените статью