Add Inline style with css variable in next.js - next.js

Doing components for app. For section want to add ability to pass some optional accent color to get output like:
<section style="--mycolor:red">
... //contents
</section>
where "red" can be passed in backend during page build as color name, #hex, "rgba()" or "hsla()" strings. It gives opportunity to use that color to children elements of this section - for border colors, first letters, markers, backgrounds etc.
Simple code^:
<section style={`--mycolor:{color}`};>
does not work because next expects mappable code, but looks like css variables names aren't parse-able in inline syntax.
I can also inject it with <style jsx> statement:
<style jsx>{`
section{
--mycolor: ${ color != '' ? color : 'var(--default-color)'};
}
`}
</style>
but this soluition looks "dirty" for such simple task - adds tons of unnecessary code just to serve one css rule.
I think it can be achieved with something like
<section styles={myStyle}>
where myStyle is jsx style object, but i don't understand how to manually create it (in examples its only imported prop w/o details where did it get from).
So is there a way to achieve simple output like <section style="--mycolor:red"> ?

#juliomalves, thanks for help, final solution is like
style={{ '--mycolor': color }}>
where:
'--mycolor' = css variable name quoted as string (css properties are not quoted !)
color = prop of an element

If using TypeScript with Nextjs, there is very simple solution as blow
{{ ['your css variable name' as any] : your value}}
e.g.
['--rating' as any]: 2.5,
['--star-color' as any]: '#b3b3b3',

incase if you want to insert inline styling using style tag in next.js , you have to insert an object inside the style={} tag as all of the style and classNames in next are considered as object . For example you want to insert the background colour of your div using the insline styling than do the followings
<div style={{ ["background-color" as any]: "#ffc107" }}></div>
do make sure that You use semicolons to insert style properties

Related

How to target elements with a specific data attribute with Tailwind CSS?

I have several message boxes and each box has a data-author attribute.
If I want to apply styles to these message boxes in CSS, I can just do:
[data-author="Ben"] {
background-color: blue;
}
But I'm not sure how to do this with Tailwind CSS or whether it's even possible. Any idea?
Thanks
You can do this by adding a variant. In your tailwind.config.js:
Add const plugin = require('tailwindcss/plugin') at the top of the page.
Then in your export add:
plugins: [
plugin(({ addVariant }) => {
addVariant('ben', '&[data-author="Ben"]')
}),
]
All you have to do is then use it how you want: ben:bg-blue-500
You would need to create a new one for each individual author though, or come up with a convention for grouping them by colors.
Updated answer as of 2022/10/30
As of Tailwind v3.2, data attribute variants are supported.
<!-- Will apply -->
<div data-size="large" class="data-[size=large]:p-8">
<!-- ... -->
</div>
<!-- Will not apply -->
<div data-size="medium" class="data-[size=large]:p-8">
<!-- ... -->
</div>
See here: https://tailwindcss.com/blog/tailwindcss-v3-2#data-attribute-variants
you can use the syntax you used above. for implementation problems, you can use the #apply directive which can directly call the utility class from tailwind
In addition, you can also apply a color that is outside the tailwind color by using an arbitrary value
[data-author="Ben"] {
#apply bg-[#bada55];
}
You can learn more about arbitary value in this article:
https://tailwindcss.com/docs/adding-custom-styles#using-arbitrary-values
This isn't possible with tailwind, you can only target elements by giving them classes. However, you can still write custom CSS and add styles to it with tailwind's #apply:
[data-author="Ben"] {
#apply bg-blue-500;
}
I think you are looking for the best syntax for state selection:
<a class="bg:blue[data-author=Ben]" data-author="Ben">Ben</a>
All native CSS selectors can be applied:
<button class="opacity:.5[disabled]" disabled>Submit</button>
It's enabled with zero configuration and the syntax is very similar to native CSS.

Inline css in the react not working dynamically

I want to show my image in background by using inline CSS in <div> tag
<div style={{backgroundImage: 'url(${imageUrl})'}}></div>
but its not working its showing unexpected template string expression.
image is about sc of the code
You should use Template literal, when you want to print dynamic value in string like,
<div style={{ backgroundImage: `url(${imageUrl})` }}
Notice the back tick (`)

How to set a CSS class name comes from an array of json object inside ngFor | Angular 6

I have a loop where i display dynamically icons, the position of the icons are styled by css on style.css, but the classes name are actually an elements of json object.
The problem is how to use the value of the json element which is style in order to style the icons.
The *ngFor looks like this:
<div *ngFor="let count of counters; let i = index" class="{{count.style}} dispanserDiv ">
<span class="dispLabel"> {{count.name }}</span>
<img (click)="openStockModal(stockModal)" class="dispanser" src="../assets/icons/dispanserIcons/0.png">
</div>
also i tried [ngClass] but not working, any help is appreciate.
Well, after i opened the inspect element, and i hover over the tags i found on screen a title message with a direction arrow out of the height of the scree, so i changed the margin-top attr th icon appear again.
but i am pretty sure that when i set the class name without using the json element value, it display fine, but when i use the json element the icons appear at a different position, but i have no idea why this is happening. but it finally worked

Use variables to update internal CSS inside an angular component?

I would like to modify quite a large amount of styles on a page through a customisable panel. When a user clicks an option, the content on the page will completely change based on whatever was clicked.
This cannot be a scenario where a class is appended to a parent element and use CSS/LESS to adjust accordingly. For this scenario (for requirement reasons) the CSS needs to be internal on the angular component HTML.
Is it possible to have a value in the component TS like this:
myNewColour: "red"
That can then be used in an internal style sheet that's inside my angular component.html like this?:
<style>
.myContainer { background: myNewColour }
</style>
<!-- HTML Content -->
<div class="myContainer"> Stuff </div>
Any help with this would be appreciated! :)
"Internal in the HTML template" is called inline style ;) Apart from that, you can use ngStyle like so
<tag [ngStyle]="{'background': myNewColour}"></tag>
EDIT if it makes your code too long, what you can do is simply
let customStyle = {
'background': this.myNewColour
};
And in your tag, simply
<tag [ngStyle]="customStyle"></tag>

Select elements with same attribute value

Is there any way to select elements with same attribute value which I don't exactly have access to? I imagine doing it in way like this:
.first[attribute=.second[attribute]]
I want to use ONLY pure CSS.
no, there is no way to achieve this using css
however, if you need to do something like this you should consider changing your markup (ex. using additional classes) - css is not a programming language
CSS cannot do that. For comparing two elements you need to have access to DOM.
We cannot achieve this through css but this can be done by JavaScript:
window.onload=function(){
var attr = 'elementValue',
elements=document.querySelectorAll('.first, .second');
console.log(
elements[0].getAttribute(attr) ===
elements[1].getAttribute(attr)
);
}
<div class="first" elementValue="1">hello</div>
<div class="second" elementValue="1">hello</div>
Hope this helps

Resources