- CSS content and attr
- Basic content Usage
- content and attr
- content Concatenation
- CSS Before and CSS After – How to Use the Content Property
- Prerequisite
- Accepted Values
- String
- Advanced Quotes
- Images
- Outside of Pseudo Elements
- Conclusion
- Thanks for reading!
- How to access and use data attributes in your CSS
- Targeting data attributes with CSS
- Getting a data attribute’s value in CSS
- Browser Compatibility
- attr ( )
- Кратко
- Пример
- Как пишется
- Подсказки
- На практике
- Денис Ежков советует
CSS content and attr
CSS is becoming more and more powerful but in the sense that it allows us to do the little things easily. There have been larger features added like transitions, animations, and transforms, but one feature that goes under the radar is generated content. You saw a bit of this with CSS counters, where we used the counter and counters expressions to set the content of a given element. There’s another expression, attr , that allows for CSS-based content creation as well. Let me show you how attr an content can work together!
Basic content Usage
The content property allows the developer to statically or (somewhat) dynamically set the content of a pseudo-element:
Remember to make the element (not the pseudo-element) position: relative if you plan to absolutely position the pseudo-element.
content and attr
In the case that you’d like to use an element attribute as content (this being the dynamic usage of content), you may do so with the attr expression:
attr is typically used with custom data- attributes since traditional element attributes are good for functionality but not so much or text presentation.
content Concatenation
Concatenating strings is done via simple spacing:
Trying to concatenate via JavaScript «+» or any other symbol will bomb . not that I found that out the hard way or anything.
The ability to use generated content with an attr expression is quite exciting. You can see this used within PrismJS’ line-highlighting plugin and a line-number plugin I’ll release soon. These generated content tactics make pseudo-elements all the more valuable too!
CSS Before and CSS After – How to Use the Content Property
Jesse Hall
The content property in CSS defines the content of an element. You may have heard that this property only applies to the ::before and ::after pseudo-elements. In this article, we’ll explore various use cases for the content property, including outside of pseudo-elements.
Prerequisite
Since the majority of the use cases for the content property involve pseudo-elements, I would suggest that you be familiar with how the ::before and ::after pseudo-elements work. Here is a great article to get you up to speed:
Accepted Values
First, let’s take a look at all of the accepted values of the content property.
- normal : This is the default value. Computes to none when used with pseudo-elements.
- none : A pseudo-element will not be generated.
- : Sets the content to the string specified. This string can contain Unicode escape sequences. For example, the copyright symbol: \\000A9 .
- : Sets the content to an image or gradient using url() or linear-gradient() .
- open-quote | close-quote : Sets the content to the appropriate quote character referenced from the quotes property.
- no-open-quote | no-close-quote : Removes a quote from the selected element, but still increments or decrements the nesting level referenced from the quotes property.
- attr(*attribute*) : Sets the content as the string value of the selected elements selected attribute.
- counter() : Sets the content as the value of a counter , usually a number.
String
One of the most basic examples would be the use of adding string content before or after an element. In this example, we’ll add a link symbol before a link and add the URL for the link after it.
Notice the space after the Unicode character in the ::before pseudo-element and the before the first parenthesis in the ::after pseudo-element. This will create space between these and the parent element.
Alternatively, you could add padding or margin to the pseudo-elements to add separation.
Advanced Quotes
We can also specify where we do not want quotes. For example, you may be quoting someone who is quoting another person. So you would have quotes within quotes, which can get confusing to the reader.
In the CodePen below, we are using HTML tags, then specifying which tags should not display the quotes.
At first glance, you might think that we should just remove the tag where needed. But by specifying where a quote should not be still increments or decrements the nesting level referenced from the quotes property.
To explain this, we need to understand the quotes property. This is simply an «array» of characters that should be used when quoting. Here is an example:
These are sets of quotes. The first set will be used for the top level of quotes. The second set will be used for the first nested quote. And the third set will be used for the second nested quote. And so on, if there were more sets included.
Now that we understand the quotes property, I can explain how the no-open-quote and no-close-quote properties work.
For each level of quotes, we can assign different sets of characters to use for the quotes. By specifying where a quote should not be still increments or decrements the nesting level referenced from the quotes property.
Take a look at the example below. You will see that the second level of quotes is skipped.
You could use this to customize content within each list item that needs a corresponding number. Or you could use this to customize the list item itself. For instance, you could remove the default numbering and implement a custom-styled numbering system.
Images
Images and gradients can be used with the content property. This is fairly straight-forward. Here is an example that uses both:
For accessibility, there is also an option to add alternate text for the image. This feature is not fully supported though.
content: url(//unsplash.it/200/200) / "Alternative Text Here";
Outside of Pseudo Elements
That’s right! You can use the content property outside of the pseudo-elements ::before and ::after . Although, its use is limited and not fully compatible in all browsers.
The most compatible use case would be replacement of an element.
Conclusion
Most times you will see content: «» found in the ::before and ::after pseudo-elements. But the content property has many useful applications.
The best use in my opinion is to use it for updating bulk elements. If you want to add an icon before every link on your site, it would be much easier to add it through the content property than to add it to every element in the HTML document.
Thanks for reading!
Thank you for reading this article. Hopefully, it has helped you to better understand how the content property works in CSS.
I’m Jesse from Texas. Check out my other content and let me know how I can help you on your journey to becoming a web developer.
How to access and use data attributes in your CSS
I use data attributes all the time in my JavaScript. But did you know that you can also use them in your CSS?
Today, I’m going to show you how to target them as selectors, and (way more cool) access their values and do things with them.
Targeting data attributes with CSS
You use # for IDs ( #main ), and . for classes ( .click-me ).
But you can also target data attributes by wrapping them in square brackets ( [] ).
[data-some-component] font-weight: bold; font-size: 1.2em; >
For a use case like that, you’re better served with a class, but sometimes it’s helpful to be able to scope selectors by only elements with a specific data attribute.
Note: This can be used for all sorts of other attributes, too, like title , src , alt and more. I’ll cover that in another article.
A more powerful use, though, is accessing the actual content of a data attribute.
Getting a data attribute’s value in CSS
You can access the content of a data attribute with the attr() CSS function. In every major browser, it’s use is limited to the content property.
For example, let’s say you wanted to add some content dynamically to a component based on a data attribute value. You could do this.
div data-content="Some content goes here.">div>
And in your CSS, you do this.
[data-content]:before content: attr(data-content); >
With this example, that content is better served in the markup itself. But when you need to use the content property and want dynamic content, this is a cool way to do it.
A quick accessibility note: some screenreader/browser combos do not read text rendered with content , so critical content should always go in the markup.
Browser Compatibility
Both attribute selectors and the attr() function work in all major browsers. Attribute selectors also work back to IE7, while the attr() function works in IE8 and up.
Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.
Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.
attr ( )
Хотите сделать атрибут элемента видимым на странице? Используйте эту функцию!
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
attr ( ) — это CSS-функция, которая умеет получать значение любого атрибута элемента, а потом использовать это значение прямо в стилях.
Пример
Скопировать ссылку «Пример» Скопировано
div class="element" title="На самом деле внутри нет никакого текста">div>
div::before content: "Элемент с классом " attr(class);> div::after content: "Подсказка: " attr(title);>
div::before content: "Элемент с классом " attr(class); > div::after content: "Подсказка: " attr(title); >
Как пишется
Скопировать ссылку «Как пишется» Скопировано
div::before content: attr(data-title); content: attr(href);>
div::before content: attr(data-title); content: attr(href); >
div::before content: attr(src url); content: attr(data-count number); content: attr(data-width px);>
div::before content: attr(src url); content: attr(data-count number); content: attr(data-width px); >
С указанием фолбэка, то есть запасного значения:
div::before content: attr(data-count number, 0); content: attr(src url, ""); content: attr(data-width px, inherit); content: attr(data-something, "default");>
div::before content: attr(data-count number, 0); content: attr(src url, ""); content: attr(data-width px, inherit); content: attr(data-something, "default"); >
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Функцию attr ( ) можно использовать в качестве значения любого CSS-свойства, однако полностью поддерживается только свойство content . Для остальных свойств поддержка экспериментальная и может различаться от браузера к браузеру. Актуальную информацию о поддержке можно посмотреть на Can I use.
💡 Написание с указанием типа или фолбэка пока имеет статус экспериментальной технологии и не поддерживается браузерами. Но в будущем это позволит гораздо сильнее расширить область применения функции attr ( ) . Например, мы сможем написать так:
.colored background-image: attr(data-src url);>
.colored background-image: attr(data-src url); >
Тут мы указали, что в качестве значения для свойства background — image мы хотим использовать значение атрибута data — src . При этом уточнили, что значение атрибута data — src — это не просто строка, а корректный URL.
Примеры записи с указанием типа или фолбэка кажутся довольно перспективными, но, к сожалению, пока не поддерживаются ни одним из браузеров.
На практике
Скопировать ссылку «На практике» Скопировано
Денис Ежков советует
Скопировать ссылку «Денис Ежков советует» Скопировано
🛠 Самый распространённый случай использования функции attr ( ) — отображение значения атрибута href после текста ссылки при печати страницы.
Подробнее о скидках и акциях можно узнать по ссылке
p> Подробнее о скидках и акциях можно узнать a href="http://best-site.ru/sales">по ссылкеa> p>
@media print a::after content: " [" attr(href) "]"; >>
@media print a::after content: " [" attr(href) "]"; > >