Css background url attr

CSS установить background-image с помощью data-image attr

показать границу правильно, но ничего не произошло для фона Как я могу исправить этот код только css (не js или jq)?

3 ответа

С точки зрения написания поддержка браузера attr() нотации браузера по свойствам CSS, отличным от content — like background-image , — очень ограниченный.

Кроме того, согласно спецификации уровня 2 CSS, объединение url() и attr() недействительно:
content: url(attr(data-image)); .

Следовательно, на данный момент нет кросс-браузерного решения CSS для достижения желаемого результата. Если использование JavaScript не является вариантом:

var list = document.querySelectorAll("div[data-image]"); for (var i = 0; i

Ограничение да, attir (данные) работает в большинстве браузеров, но версия CSS3 attr (резервный тип данных) не поддерживается. Посмотреть статус браузера для CSS3 attr

Проблемы:

Это ваш ответ. Проверьте эту документацию в w3.org. Но главная проблема: она не будет работать, еще нет!. Во многих браузерах attr() выполняется успешно, когда он используется в атрибуте content: для кодирования CSS. Но используя его в других атрибутах CSS, он работает не так, как ожидалось, даже в крупных браузерах.

Обратите внимание, что url( attr(data-image) ) определенно неверен. В соответствии с модулем уровня 3 «Значения и единицы измерения CSS» нотация url() принимает в качестве URI только / заключенный в кавычки . OP уже использовал действительный синтаксис attr() , но он еще не реализован в браузерах.

Как я уже упоминал, OP использовал правильный синтаксис: attr(data-image url) который указан в спецификации . Новый синтаксис attr() : attr( ? [ , ]? ) Где необязательный указывает тип данного и будет значением по умолчанию, если именованный атрибут отсутствует.

@HashemQolami, спасибо за вашу ценную помощь. Я никогда ничего не узнал из документации, все, что я узнал, из учений человека. Но я все еще включаю ссылки на документацию для устранения проблем с спрашивающими.

Источник

attr()

Note: The attr() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse.

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element’s originating element is returned.

Try it

Syntax

/* Simple usage */ attr(data-count); attr(title); /* With type */ attr(src url); attr(data-count number); attr(data-width px); /* With fallback */ attr(data-count number, 0); attr(src url, ""); attr(data-width px, inherit); attr(data-something, "default"); 

Values

The name of an attribute on the HTML element referenced in the CSS.

Читайте также:  Html update menu on all pages

A keyword representing either the type of the attribute’s value, or its unit, as in HTML some attributes have implicit units. If the use of as a value for the given attribute is invalid, the attr() expression will be invalid too. If omitted, it defaults to string . The list of valid values are:

Default value: an empty string.

The attribute value is parsed as a hash (3- or 6-value hash) or a keyword. It must be a valid CSS value. Leading and trailing spaces are stripped.

Default value: currentcolor .

The attribute value is parsed as a string that is used inside a CSS url() function. Relative URL are resolved relatively to the original document, not relatively to the style sheet. Leading and trailing spaces are stripped.

Default value: the URL about:invalid that points to a non-existent document with a generic error condition.

Default value: 0 , or, if 0 is not a valid value for the property, the property’s minimum value.

Default value: 0 , or, if 0 is not a valid value for the property, the property’s minimum value.

Default value: 0 , or, if 0 is not a valid value for the property, the property’s minimum value.

em , ex , px , rem , vw , vh , vmin , vmax , mm , cm , in , pt , or pc Experimental

Default value: 0 , or, if 0 is not a valid value for the property, the property’s minimum value.

Default value: 0deg , or, if 0deg is not a valid value for the property, the property’s minimum value.

deg , grad , rad Experimental

Default value: 0deg , or, if 0deg is not a valid value for the property, the property’s minimum value.

Default value: 0s , or, if 0s is not a valid value for the property, the property’s minimum value.

Default value: 0s , or, if 0s is not a valid value for the property, the property’s minimum value.

Default value: 0Hz , or, if 0Hz is not a valid value for the property, the property’s minimum value.

Default value: 0Hz , or, if 0Hz is not a valid value for the property, the property’s minimum value.

Default value: 0% , or, if 0% is not a valid value for the property, the property’s minimum value.

The value to be used if the associated attribute is missing or contains an invalid value. If not set, CSS will use the default value defined for each .

Formal syntax

=
attr( ? , ? )

=
string |
url |
ident |
color |
number |
percentage |
length |
angle |
time |
frequency |
flex |

Источник

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) "]"; > >      

Источник

CSS set background-image by data-image attr

a nice alternative to data- attributes (or the attr() approach in general) can be the use of custom properties (MDN, csswg, css-tricks).

as their values are not restricted to strings, we can pass around any type that is allowed as a custom property value!

also, you get the benefit of updating these properties at runtime, with a swap of a stylesheet.

Solution 2

As of writing, the browser support of attr() notation on CSS properties other than content — like background-image — is very limited.

Besides, as per CSS level 2 spec, combining url() and attr() is not valid:
content: url(attr(data-image)); .

Hence there is no cross-browser CSS solution at the moment to achieve the desired result. Unless using JavaScript is an option:

var list = document.querySelectorAll("div[data-image]"); for (var i = 0; i

Solution 3

In your HTML:

In your CSS:

Problems:

This is your required answer. Check this documentation in w3.org. But the main problem is it won’t work, not yet!. In many browsers, attr() runs successfully when it is used in content: attribute of the CSS coding. But using it in other attributes of CSS, it doesn’t work as expected, not even in major browsers.

Solution 4

If the goal is being able to set the background-image style of an HTML element from within the HTML document rather than the CSS definition, why not use the inline style attribute of the HTML element?

If selecting the by style is not an option, you may be able to give it a class and select it by class name.

Hossain Khademian

Hossain Khademian

I’m a professional Android App Developer. I enjoy exploring new things, techs and frameworks. I have 5 years experience in Native Android App Development plus 2 years in Kotlin language and 3 years in NodeJS for server-side scripting. I actively tries to learn new things and importantly enhance the previous ones I love robotics, space, aliens, computers, romance, music, and . internationalization!

Comments

Hossain Khademian

border show correctly but nothing happened for background How can do I fix this code only with css (not js or jq)?

Note that url( attr(data-image) ) is definitely wrong. According to CSS Values and Units Module Level 3, url() notation only accepts bare/quoted as URI. The OP has already used the valid syntax of attr() , but it is not implemented in browsers yet.

@HashemQolami, thank you. But I didn’t understand the documentation of url. What exactly will come in place of url( attr() ) ??

As I mentioned, the OP used the valid syntax: attr(data-image url) which is stated by the spec. The new syntax of attr() is: attr( ? [ , ]? ) where optional specifies the type of the given and the would be the default value if named attribute is missing.

@HashemQolami, thank you for your valuable help. I never learnt anything from documentations, everything I learn is from a person’s teachings. But, I still include the links to documentation for clearing problems to questioners.

Источник

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