How to add content to css

content

Свойство, с помощью которого можно добавить на страницу то, чего нет в HTML-разметке.

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Когда задано свойство content , то элемент заменяется на значение этого свойства. В качестве значения могут быть переданы различные типы: изображение, градиент или текст.

Пример

Скопировать ссылку «Пример» Скопировано

 a::after  content: "👉"; margin-right: 5px;> a::after  content: "👉"; margin-right: 5px; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Изображение в качестве содержимого. Может применяться к любому элементу.

 div  content: url("http://www.example.com/test.png");> div  content: url("http://www.example.com/test.png"); >      

Все значения ниже могут применяться ТОЛЬКО к псевдоэлементам : : before и : : after .

 div::before  content: "prefix";> div::before  content: "prefix"; >      

Значения счётчиков с использованием функций counter ( ) и counters ( ) :

 div::before  content: counter(chapter_counter);> div::before  content: counters(section_counter, ".");> div::before  content: counter(chapter_counter); > div::before  content: counters(section_counter, "."); >      

Значения HTML-атрибутов с использованием функции attr ( ) :

 div::before  content: attr(value string);> div::before  content: attr(value string); >      

Ключевые слова, зависящие от языка страницы и положения в тексте:

 div::before  content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote;> div::before  content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote; >      

Использование нескольких значений одновременно. Исключение — ключевые слова normal и none :

 div::before  content: open-quote counter(chapter_counter);> div::before  content: open-quote counter(chapter_counter); >      

Ключевые слова, которые нельзя комбинировать с другими значениями:

 div::before  content: normal; content: none;> div::before  content: normal; content: none; >      

Как понять

Скопировать ссылку «Как понять» Скопировано

Чаще всего свойство content применяется к псевдоэлементам : : before и : : after . В зависимости от значения свойства псевдоэлемент принимает тот или иной вид:

  • Если значением является просто строка, то она подставляется на место псевдоэлемента. Как правило, это до или после текстового содержимого тега.
  • Есть несколько зарезервированных слов, которые также можно указывать в качестве значения. Используются они как совместно со свойством quotes , так и в автоматическом режиме:
    • open — quote обозначает открывающую кавычку цитаты для текущего языка. Например, для русского это будет открывающая «ёлочка» ( « );
    • close — quote обозначает закрывающую кавычку цитаты для текущего языка. Например, для русского это будет закрывающая «ёлочка» ( » );
       Вспомните, как говорили мушкетёры: Один за всех, все за одного!  blockquote> Вспомните, как говорили мушкетёры: q>Один за всех, все за одного!q> blockquote>      
     blockquote  quotes: "«" "»" "„" "”";> blockquote::before  content: open-quote;> blockquote::after  content: close-quote;> blockquote  quotes: "«" "»" "„" "”"; > blockquote::before  content: open-quote; > blockquote::after  content: close-quote; >      
    «Вспомните, как говорили мушкетёры: „Один за всех, все за одного!”»
    • no — open — quote и no — close — quote используются, когда не нужно отображать кавычки, но при этом продолжать увеличивать уровень вложенности;
    • Если значением является результат выполнения функций counter ( ) или counters ( ) , то псевдоэлемент будет содержать вычисленное значение счётчика в текущий момент. Эти функции работают совместно со свойствами counter — reset и counter — increment ;
    • Очень интересным значением является результат выполнения функции attr ( ) .

    С помощью неё можно вывести в псевдоэлемент значение любого атрибута тега:

       Ваш рейтинг: 212  p> Ваш рейтинг: span data-tip="Вычисляется на основе активности">212span> p>      
     [data-tip]  position: relative; cursor: help;> [data-tip]:hover::after  opacity: 1; visibility: visible;> [data-tip]::after  content: attr(data-tip); position: absolute; top: 140%; left: 50%; transform: translateX(-50%); opacity: 0; visibility: hidden;> [data-tip]  position: relative; cursor: help; > [data-tip]:hover::after  opacity: 1; visibility: visible; > [data-tip]::after  content: attr(data-tip); position: absolute; top: 140%; left: 50%; transform: translateX(-50%); opacity: 0; visibility: hidden; >      

    Вывод ссылки на печать

    🛠 . или красиво оформить нумерованный перечень

     .benefits  counter-reset: benefits;> .benefits-item  counter-increment: benefits;> .benefits-item::before  content: counter(benefits); position: absolute; font-size: 190px; font-weight: bold; left: 0; top: -0.35em; opacity: 0.5; color: #1A5AD7;> .benefits  counter-reset: benefits; > .benefits-item  counter-increment: benefits; > .benefits-item::before  content: counter(benefits); position: absolute; font-size: 190px; font-weight: bold; left: 0; top: -0.35em; opacity: 0.5; color: #1A5AD7; >      

    Источник

    Using CSS generated content

    This article describes some ways in which you can use CSS to add content when a document is displayed. You modify your stylesheet to add text content or images.

    One of the important advantages of CSS is that it helps you to separate a document’s style from its content. However, there are situations where it makes sense to specify certain content as part of the stylesheet, not as part of the document. You can specify text or image content within a stylesheet when that content is closely linked to the document’s structure.

    Note: Content specified in a stylesheet does not become part of the DOM.

    Specifying content in a stylesheet can cause complications. For example, you might have different language versions of your document that share a stylesheet. If you specify content in your stylesheet that requires translation, you have to put those parts of your stylesheet in different files and arrange for them to be linked with the appropriate language versions of your document.

    This issue does not arise if the content you specify consists of symbols or images that apply in all languages and cultures.

    Examples

    Text content

    CSS can insert text content before or after an element, or change the content of a list item marker (such as a bullet symbol or number) before a or other element with display: list-item; . To specify this, make a rule and add ::before , ::after , or ::marker to the selector. In the declaration, specify the content property with the text content as its value.

    HTML

    span class="ref">somethingspan> 

    CSS

    .ref::before  font-weight: bold; color: navy; content: "Reference "; > 

    Output

    The character set of a stylesheet is UTF-8 by default, but it can also be specified in the link, in the stylesheet itself, or in other ways. For details, see 4.4 CSS style sheet representation in the CSS Specification.

    Individual characters can also be specified by an escape mechanism that uses backslash as the escape character. For example, «\265B» is the chess symbol for a black queen ♛. For details, see Referring to characters not represented in a character encoding and Characters and case in the CSS Specification.

    Image content

    To add an image before or after an element, you can specify the URL of an image file in the value of the content property.

    This rule adds a space and an icon after every link that has the class glossary :

    HTML

    a href="developer.mozilla.org" class="glossary">developer.mozilla.orga> 

    CSS

    a.glossary::after  content: " " url("glossary-icon.gif"); > 

    Found a content problem with this page?

    This page was last modified on Jun 30, 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.

    Источник

    How to add content to an Element using CSS

    www.encodedna.com

    You can use the CSS content property to add text contents to an element in your web page. However, this property can only be used with pseudo elements like ::before and ::after .

    For example, I have a list of stationary goods on my web page, against which I want to add a star or the asterix character (not the comic character), but the symbol * ) if the goods are not in my inventory.

    <!DOCTYPE> <html> <head> <title>CSS content Property Example</title> <style> .outOfStock::after < color: red; content: " *"; > </style> </head> <body> <p>Using CSS "content" property to add a "*" character after an item!</p> <ul> <li>highlighters</li> <li>pencils</li> <li>erasers</li> <li >scrapbooks</li> <li >paper clips</li> </ul> </body> </html>

    In the above example, the character * (or asterix) shows against two items, which has the class outOfStock defined. The * symbol shows after each item name, since I have used the CSS content property using the pseudo element ::after . See the &ltstyle> section in the markup.

    Note : You can use other characters like \2193 . It shows a down arrow.

    Chrome 39.0 — Yes | Firefox 34.0 — Yes | Internet Explorer 8 and above — Yes | Safari — Yes | Opera 4+ — Yes

    Using CSS “content” Property with “::before” Pseudo Element

    Similarly, you can use the pseudo element ::before with the content property. For example,

    <!DOCTYPE> <html> <head> <title>CSS content Property Example</title> <style> .inStock::before < color: red; content: "\2713 "; > </style> </head> <body> <p>CSS "content" property with pseudo element ::before!</p> <ul> <li >highlighters</li> <li >pencils</li> <li >erasers</li> <li>scrapbooks</li> <li>paper clips</li> </ul> </body> </html>

    Note: You can apply both ::before and ::after with CSS content property. For example,

    <!DOCTYPE> <html> <head> <title>CSS content Property Example</title> </head> <body> <style> ul < display: table; margin: 0; padding: 0; >ul li < list-style: none; >.inStock::before < color: red; content: "* "; > .inStock::after < color: red; content: " *"; > </style> <p>CSS "content" with pseudo elements ::before and ::after.</p> <ul> <li >highlighters</li> <li >pencils</li> <li >erasers</li> <li>scrapbooks</li> <li>paper clips</li> </ul> </body> </html>

    See the space I have added before and after the * with the content property.

    Using CSS content Property Dynamically

    You cannot add the pseudo elements ::before and ::after using JavaScript. However, you can add a class name, with the pseudo elements, which also have the CSS content property, dynamically using JavaScript. This will do the trick. Here’s an example,

    Well, that’s it. You can add texts, symbols, numbers, Unicode (or decimal code), images, hyperlinks etc., to an element using the CSS content property.

    Browser Support:
    Chrome 39.0 — Yes | Firefox 34.0 — Yes | Internet Explorer 8 and above — Yes | Safari — Yes | Opera 4+ — Yes

    Источник

    Читайте также:  Initialize constant in java
Оцените статью