Property value expected css что это
@property: наделение CSS-переменных сверхспособностями
CSS Houdini — это общий термин, который охватывает набор низкоуровневых API-интерфейсов раскрывающих части механизма рендеринга CSS и предоставляющих разработчикам доступ к объектной модели CSS. Это огромное изменение для экосистемы CSS, потому что оно позволяет разработчикам указывать браузеру, как читать и анализировать пользовательский CSS, не дожидаясь, пока поставщики браузеров предоставят встроенную поддержку этих функций.
Одним из самых интересных дополнений к CSS в рамках Houdini является API свойств и значений. Этот API-интерфейс расширяет пользовательские CSS-свойства (обычно называемые CSS-переменными), придавая им семантическое значение (определяемое синтаксисом) и даже резервные значения, позволяя тестировать CSS.
Написание пользовательских Houdini-свойств
Вот пример установки настраиваемого свойства (можно считать: CSS-переменной), но теперь у него есть поля: syntax (c типом), initial-value (с начальным значением) и inherits (наследует ли оно значение от своего родителя). То же самое можно сделать с помощью JavaScript — CSS.registerProperty(), но в Chromium 85 и более поздних версиях синтаксис @property поддерживает уже в CSS:
В JavaScript (Chromium 78)
В CSS (Chromium 85)
Важно: при написании зарегистрированного настраиваемого свойства с указанным syntax требуется указать initial-value (начальное значение).
Резервные значения
Как для любого другого настраиваемого свойства, здесь можно получать (используя var) или устанавливать (записывать/перезаписывать) значения. Но с настраиваемыми Houdini-свойствами, если при переопределении установить неожиданное для него значение, механизм визуализации CSS вместо игнорирования строки отправит предустановленное начальное значение.
Syntax
Используя syntax теперь можно писать семантический CSS с указанием типа. К текущим разрешенным типам относятся:
Установка syntax позволяет браузеру проверять тип настраиваемых свойств (CSS-переменных). Это дает много преимуществ.
Чтобы проиллюстрировать этот момент, рассмотрим, как анимировать градиент. В настоящее время нет возможности плавно анимировать (или интерполировать) между значениями градиента, поскольку каждое объявление градиента анализируется как строка.
Браузер слева поддерживает API Houdini- свойств и значений. Это обеспечивает плавный переход с установкой градиента. В браузере справа нет такой поддержки и он может воспринимать это только как изменение значения строки с одного сразу на другое. Невозможность интерполировать значения приводит к отсутствию эффектного плавного перехода.
А когда придет время его анимировать, можно обновить значение с начальных 40% до 100% :
Теперь это поможет реализовать для градиента плавный переход.
Плавная анимация градиентной рамки.
Заключение
Правило @property делает захватывающую технологию ещё доступнее, позволяя писать семантически значимый CSS внутри самого CSS. Чтобы узнать больше о Houdini-CSS и API Houdini- свойств и значений, ознакомьтесь с этими ресурсами:
css calc invalid property value
Can someone tell me why this CSS calc function isn’t working? When I inspect element on Chrome, it says ‘Invalid property value’.
6 Answers 6
For future googlers:
Incorrect (invalid property value):
The OP’s question above does not have this problem, but while googling an answer to this error message this is the first resource I found, so it should have an answer dedicated to this common error.
When using calc() you can’t divide by pixels, you can only divide by unitless numbers. Also, the number you are dividing has to have a certain unit like px, em, vh, vw.
For example, if you need to set a width of an element you should use:
An important note is to make sure you put spaces between the operator signs. This calc() article provides further detailed explanation on the function.
As Stephen Thomas has answered, you can’t divide by units. To get around this, just divide the numbers as numbers and then assign the unit of measurement by multiplying the result by 1 unit of the units you’re interested in. In your nested scenario you’d need to figure out what unit of measurement you were after in the end so that you could divide the numbers and then assign the result to a px or vw unit of measurement.
As @cssyphys noted above, you have to have spaces around your minus sign. However, if you are using ASP.NET MVC’s bundler/minifier you find that it removes the spaces so you get the noted error.
If you are using plain CSS3, the following expression can be used in CSS and won’t get minified:
Using CSS custom properties (variables)
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., —main-color: black; ) and are accessed using the var() function (e.g., color: var(—main-color); ).
Custom properties are subject to the cascade and inherit their value from their parent.
Basic usage
Note that the selector given to the ruleset defines the scope that the custom property can be used in. A common best practice is to define custom properties on the :root pseudo-class, so that it can be applied globally across your HTML document:
However, this doesn’t always have to be the case: you maybe have a good reason for limiting the scope of your custom properties.
As mentioned earlier, you use the custom property value by specifying your custom property name inside the var() function, in place of a regular property value:
First steps with custom properties
Let’s start with this simple CSS that applies the same color to elements of different classes:
We’ll apply it to this HTML:
. which leads us to this:
Using the :root pseudo-class
Notice the repetitive CSS in the example above. The background color is set to brown in several places. For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally. For non-trivial projects, this is not always possible. By declaring a custom property on the :root pseudo-class and using it where needed throughout the document, a CSS author can reduce the need for repetition:
This leads to the same result as the previous example, yet allows for one canonical declaration of the desired property value; very useful if you want to change the value across the entire page later.
Inheritance of custom properties
Custom properties do inherit. This means that if no value is set for a custom property on a given element, the value of its parent is used. Take this HTML:
. with the following CSS:
In this case, the results of var(—test) are:
Keep in mind that these are custom properties, not actual variables like you might find in other programming languages. The value is computed where it is needed, not stored for use in other rules. For instance, you cannot set a property for an element and expect to retrieve it in a sibling’s descendant’s rule. The property is only set for the matching selector and its descendants, like any normal CSS.
Custom property fallback values
Using the var() function, you can define multiple fallback values when the given variable is not yet defined; this can be useful when working with Custom Elements and Shadow DOM.
Note: Fallback values aren’t used to fix the browser compatibility. If the browser doesn’t support CSS custom properties, the fallback value won’t help. It’s just a backup for the browser which supports CSS custom properties to choose a different value if the given variable isn’t defined or has an invalid value.
The first argument to the function is the name of the custom property to be substituted. The second argument to the function, if provided, is a fallback value, which is used as the substitution value when the referenced custom property is invalid. The function only accepts two parameters, assigning everything following the first comma as the second parameter. If that second parameter is invalid, such as if a comma-separated list is provided, the fallback will fail. For example:
Including a custom property as a fallback, as seen in the second example above, is the correct way to provide more than one fallback. The technique has been seen to cause performance issues as it takes more time to parse through the variables.
Note: The syntax of the fallback, like that of custom properties, allows commas. For example, var(—foo, red, blue) defines a fallback of red, blue — anything between the first comma and the end of the function is considered a fallback value.
Validity and values
The classical CSS concept of validity, tied to each property, is not very useful in regard to custom properties. When the values of the custom properties are parsed, the browser doesn’t know where they will be used, so must, therefore, consider nearly all values as valid.
Unfortunately, these valid values can be used, via the var() functional notation, in a context where they might not make sense. Properties and custom variables can lead to invalid CSS statements, leading to the new concept of valid at computed time.
What happens with invalid variables?
When the browser encounters an invalid var() substitution, the initial or inherited value of the property is used.
Consider the code snippet below.
Result
The paragraph color will not be blue because invalid substitution is replaced by the initial value, not by the fallback. If you had written color: 16px without any variable substitutes, then it was a syntax error. The previous declaration will then be used.
Values in JavaScript
To use the values of custom properties in JavaScript, it is just like standard properties.
Browser compatibility
BCD tables only load in the browser
invalid property value css
Есть вот такое свойство:
Однако хром не показывает ни один из этих фонов, я уже Nцать раз проверил — синтакс правильный, а хром пишет Invalid property value. Огнелис туда же — просто игнорирует. Что такое?
Посмотреть можно здесь в самом низу.
You can do this with both the shorthand background property and the individual properties thereof except for background-color. That is, the following background properties can be specified as a list, one per background: background, background-attachment, background-clip, background-image, background-origin, background-position, background-repeat, background-size.
I have some very simple HTML/CSS code, and no matter what I do, I always get an «invalid property value» exception by chrome, and the logo won’t position properly. Thanks for any help.
Fixed the first problem, but now the image does not move related to the border. Sorry, but I’m totally new to web design and need a little bit of help.
I put the below CSS rules in database that are valid in Google Chrome:
When I try to add this rules to a div with JQuery, this rule merged as single rule and get invalid value
How do I know why it is invalid?
If you’ve identified this as a bug this is a bug with a recent version of JQuery, you should report it to the JQuery GitHub issues page; Not here.
A workaround would be to simply set the the style attribute manually.
Ошибка «property value expected css» и «at-rule or selector expected css» редактирование шаблона Go в VSCode
Но я получаю ошибки в VSCode:
ожидаемая стоимость недвижимости css(css-ожидаемая стоимость недвижимости)
at-правило или ожидаемый селектор css(css-ожидаемый селектор правил)
когда я пробую << >> в стиле html.
2 ответа
У меня есть Sass::SyntaxError: Invalid CSS after >: expected selector or at-rule, was > % RAILS_ENV=production rake assets:precompile (git)-[feature/prettier_form] (in /Users/ll/Dropbox/Rails/dqa_dev_server) rake aborted! Sass::SyntaxError: Invalid CSS after >: expected selector or at-rule, was >.
В моем проекте Ruby on Rails у меня есть какая-то странная проблема. По некоторым причинам мне пришлось переключиться с sass на less. В разработке все css работают нормально. Я вижу свой сайт с правильным дизайном. Но, когда я пытаюсь сделать некоторые тесты cucumber, я получаю ошибку с long.
Я нашел решение. Отключите html проверка стилей в vscode настройки
Привет, я исправил это, установив расширение Django в VsCode
Похожие вопросы:
Invalid CSS after >: expected selector or at-rule, was > (in /home/test/www/dispatch/app/assets/stylesheets/application.css) (sass):364 Вышеприведенная ошибка-это то, что происходит в моем.
Я работаю над базовым слайд-шоу, оно отлично работает в Firefox, однако IE дает мне следующие ошибки: Expected identifier, string or number script.js, line 26 character 4 Expected identifier, string.
Я пытаюсь использовать http://startbootstrap.com/stylish-portfolio в моем приложении rails, однако я получаю следующую ошибку в моем файле stylish-portfolio.css.scss.erb: ActionView::Template::Error.
У меня есть Sass::SyntaxError: Invalid CSS after >: expected selector or at-rule, was > % RAILS_ENV=production rake assets:precompile (git)-[feature/prettier_form] (in.
В моем проекте Ruby on Rails у меня есть какая-то странная проблема. По некоторым причинам мне пришлось переключиться с sass на less. В разработке все css работают нормально. Я вижу свой сайт с.
Я писал код в style.scss следующий код: body
Поэтому я пытаюсь настроить какой-то анимированный текст в своем проекте, но постоянно получаю ошибку в vscode, говорящую property value expected css(css-propertyvalueexpected) [59, 1] в.
Как правильно настроить попутный ветер CSS и код против, по крайней мере, отключить ошибки про правило и пустые ошибки бирка внутри VueJS один файл компонента (Вуэ-интерфейс командной строки).