Reputation: 4080
Without specifying/wrapping with a selector (button {}
), the following styled-jsx
style declarations will work. The button is properly styled which is great. However, usage like this is not documented in website so i wonder if this syntax is officially supported and safe to use?
<button>
<style jsx>{`
background-color: red;
:hover {
background-color: #ccc;
}
`}
</style>
Test
</button>
Another example, using resolve tag that works too:
const { className, styles } = css.resolve`
font-weight: bold;
`;
Upvotes: 3
Views: 353
Reputation: 1081
styled-jsx
uses stylis
css preprocessor under the hood. This is how styled-jsx
transforms content of a style tag:
transformedCss = transform(
isGlobal ? '' : getPrefix(dynamic, staticClassName),
plugins(css, pluginsOptions),
{ splitRules, vendorPrefixes }
)
Note, that transform
here is a wrapper function around stylis
.
Thus styles declared inside <style jsx>
tag will be wrapped with dynamically generated class and then transformed with stylis
.
In your case styled-jsx
will produce this css:
If you use global
selector no class selector will be added to the generated code and so produced css wont be applied to any elements on the page.
From my point of view it won't be a mistake to use styles without a selector, however, you should do it carefully with a <style jsx>
tag because in this case styles will be applied to every element inside a component.
Using this feature with css.resolve
looks much more safe since you may manually pick the elements to apply css.
As far as I know, the official documentation misses the explanation of such an important detail.
Upvotes: 2