Dynamic classes in css

How to Set the CSS Class Name Dynamically in Lesscss

Dynamically add styles in css/less by using class name

This is not possible, as far as I know, however this is a great use case for inline styling:

If you wanted to support a finite number of widths, then you can use recursion to generate classes:

.widthgen(@count) when (@count > 0) .widthgen((@count - 10)); 
.xyz_@ background-color: red;
width: @count * 1px;
>
>

.widthgen(50);
.xyz_10 background-color: red; 
width: 10px;
>
.xyz_20 background-color: red;
width: 20px;
>
.xyz_30 background-color: red;
width: 30px;
>
.xyz_40 background-color: red;
width: 40px;
>
.xyz_50 background-color: red;
width: 50px;
>

Lists Plugin

You could use the lists plugin (to install: npm install -g less-plugin-lists ) if your widths you want to support are not easily captured in a linear pattern:

@widths: 10, 20, 40, 50;

.for-each(@i in @widths) .xyz_@ background-color: red;
width: @i * 1px;
>
>

You would compile that with:

lessc --lists in.less out.css
.xyz_10 background-color: red; 
width: 10px;
>
.xyz_20 background-color: red;
width: 20px;
>
.xyz_40 background-color: red;
width: 40px;
>
.xyz_50 background-color: red;
width: 50px;
>

How to create dynamic classes in less

Try to use mixin to achieve this.

//define the mixin 
.margin-top(@value) .margin-top-@ <
margin-top:@value;
>
>
//use the mixin like this
.margin-top(20px);

U can try it here: http://winless.org/online-less-compiler

Читайте также:  Python полиномиальная линия тренда

How have dynamic class names in LESS CSS and use them as values in function

You have to create a list of colors first before creating a loop:

.make-classes(@prefix, @list) .iter(length(@list)); 
.iter(@i) when (@i > 0) .iter(@i - 1);
@pair: extract(@list, @i);
@key: extract(@pair, 1);
@value: extract(@pair, 2);
.@.color-@ color: @value;
>
>
>

@colors:
~'blue' #7FB3D4,
~'gray' #767676,
~'green' #8CC079,
~'red' #b35d5d;

.make-classes(link, @colors);
.link.color-blue color: #7fb3d4;
>
.link.color-gray color: #767676;
>
.link.color-green color: #8cc079;
>
.link.color-red color: #b35d5d;
>

Dynamic class names in LESS

I don’t think you’re far off. What I’ve done is create a second variable inside the mixin, called @index2 . All this does is find the ‘920px minus @index’ value that you’re looking for:

this is then appended to the class name:

This is the complete loop:

.loopingClass (@index) when (@index > 160) @index2 = (920-@index); 
// create the actual css selector, example will result in
// .myclass_30, .myclass_28, . , .myclass_1
(~".gs@-@") // your resulting css
width: (@index/20+1)*@col;
>
// next iteration
.loopingClass(@index - 60);
>
// "call" the loopingClass the first time with highest value
.loopingClass (@iterations);

In order to get just the set you are looking for (gs220-700 to gs700-220), just change @iterations to equal 700.

Worth noting that currently, this will create the classes in the reverse order of how you specified them in the question.

How to set the CSS class name dynamically in LessCSS?

Support was added to less.js and dotless in version 1.3

You have to use brackets and an escaping string.. e.g.

This format is deprecated. less 1.3.1 (currently just trunk build of less.js) supports a simpler syntax

Dynamic class to element with Less

If I understand you correctly, I believe you’re looking for:

table .table; 
.table-striped;
.table-hover;

/* Any other default table styles */
>

While you can’t add class=»table table-striped table-hover» to each element (that’s more in the JS-realm), you can get the same effect by using the other classes as mixins added to the default table element’s styles. See the LESS documentation for more examples.

How do I dynamically add CSS classes to HTML elements if value is less or greater than 0?

You should try binding class.
Something like that:

getDivClasses(value) return value > 0 ? "positive" : "negative";
>,

How to dynamically create CSS class in JavaScript and apply?

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass < color: #F00; >';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('someElementId').className = 'cssClass';

How to add common style in less and based on dynamic class add different styles

you can achieve this using the ampersand character to add a class to a class like below:

Источник

Create CSS classes dynamically

SASS interpolation is an useful tool that comes in handy when we have to create CSS classes name dynamically from an array.

For the first version of this blog, I wanted different gradients based on post tag (git, vsc, nodejs. ). Each tag is append to the main card class in order to create a modifier

// card.njk

article class="c-card c-card-->"> . div>
// card.scss

$co_card-gradient-git: #eb3349, #f45c43;
$co_card-gradient-vsc: #1a2980, #26d0ce;
$co_card-gradient-nodejs: #36582f, #7ab659;

.c-card--git
background: linear-gradient(to right, $co_card-gradient-git);
>

.c-card--vsc
background: linear-gradient(to right, $co_card-gradient-vsc);
>

.c-card--nodejs
background: linear-gradient(to right, $co_card-gradient-nodejs);
>

In attempt to remove repetitions and have a DRY (Don’t Repeat Yourself) code, I tried to loop through a SASS list and generate classes

$tags: git, vsc, nodejs;

@each $tag in $tags
.c-card--#
background: linear-gradient(to right, $co_card-gradient-#tag>);
>
>

but unfortunately SASS does not support variable name interpolation at the moment! 💔

If you try to compile the snippet above, you will get

Sass Error: Undefined variable: "$co_card-gradient-"

The workaround #

@mixin card-gradient($tag)  
@if $tag == 'git'
background: linear-gradient($co_card-gradient-git);
>

@else if $tag == 'vsc'
background: linear-gradient($co_card-gradient-vsc);
>

@else if $tag == 'nodejs'
background: linear-gradient($co_card-gradient-nodejs);
>
>
$tags: git, vsc, nodejs;

@each $tag in $tags
.c-card--#
@include card-gradient($tag);
>
>

Dynamic classes using CSS vars #

Note that if we use CSS vars instead of SASS vars we can interpolate the class name with #<> syntax.

@for $i from 1 through 5  
.t-palette-color--#
background-color: var(--co_palette-# );
>
>

If we need to mantain SASS vars (in my code, I needed to use darken and lighten SASS function) we could interpolate classes name like this:

$co_palette-1: #ef476f;
$co_palette-2: #ffc233;
$co_palette-3: #06d6a0;
$co_palette-4: #1b98e0;
$co_palette-5: #ff9f1c;

:root
--co_palette-1: # ;
--co_palette-2: # ;
--co_palette-3: # ;
--co_palette-4: # ;
--co_palette-5: # ;

--co_palette-1--lighten: #lighten($co_palette-1, 10%)>;
--co_palette-2--lighten: #lighten($co_palette-2, 10%)>;
--co_palette-3--lighten: #lighten($co_palette-3, 10%)>;
--co_palette-4--lighten: #lighten($co_palette-4, 10%)>;
--co_palette-5--lighten: #lighten($co_palette-5, 10%)>;
>
@for $i from 1 through 5  
.t-palette-color--# .c-card::before
background-color: var(--co_palette-# );
color: var(--co_palette-# --lighten);
>
>
.t-palette-color--1 .c-card::before  
background-color: var(--co_palette-1);
color: var(--co_palette-1--lighten);
>

.t-palette-color--2 .c-card::before
background-color: var(--co_palette-2);
color: var(--co_palette-2--lighten);
>

.t-palette-color--3 .c-card::before
background-color: var(--co_palette-3);
color: var(--co_palette-3--lighten);
>

.t-palette-color--4 .c-card::before
background-color: var(--co_palette-4);
color: var(--co_palette-4--lighten);
>

.t-palette-color--5 .c-card::before
background-color: var(--co_palette-5);
color: var(--co_palette-5--lighten);
>

Источник

doctor Brain

Итак, у нас есть класс .form-123 , в котором цифровая составляющая изменяется при загрузке или обновлении страницы. Можно ли установить единые CSS-свойства (например, margin или background-color ) для классов такого типа.

И сразу спойлер: да, это возможно, и для такой магии есть целых 3 способа.

Способ №1. Соответствие префикса

Воспользуемся CSS-селектором класса ˆ=»form-» , которые позволит выбрать все элементы, содержащие класс с префиксом form- :

Теперь для всех элементов HTML-документа:

будут установлены одинаковые CSS-свойства.

Способ №2. Совпадение значений

Здесь на помощь приходит другой CSS-селектор *=»form-» , который позоволит выбрать элементы, содержащие хотя бы одно вхождение искомой подстроки:

Способ №3. Дополнительный класс

А теперь, самый известный метод: создаем отделный класс с необходимыми CSS-свойствами:

Реквизит !important не является обязательным, но в этом случае класс, содержащий общие свойства, должен следовать после всех динамических классов.

В этом случае придется немного модифицировать HTML-документ:

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

Dynamic Classes in Tailwind CSS

If you have tried passing a dynamic value to a Tailwind CSS class, it will most likely fail to work. Although the class name is properly applied to the HTML element, the corresponding styles are not. Tailwind CSS determines what styles to bundle by parsing the files you specify in content property inside tailwindcss.config.cjs file.

module.exports =   content: ['./index.html', './src/**/*.'], >; 

Since Tailwind has a massive collection of classes, it doesn’t include them all in the final stylesheet. To reduce the size of the bundle, it only compiles the styles for classes that you mention inside your code. When Tailwind parses your source files and sees a class that contains a dynamic value, it doesn’t recognize it. Therefore those styles are not compiled.

// ❌ using a dynamic value within Tailwind CSS class p className=`text-$size>xl`>>Hellop>  // ❌ using a variable that contains a dynamic value const style = `text-$size>xl`; p className=style>>Hellop> 
let style;  if (size === 2)   // ✅ referencing a Tailwind CSS class  style = `text-2xl`; >  p className=style>>Hellop> 
// ✅ const size = 2; // size can be text-2xl or text-4xl p className=`text-$size>xl`>>Hellop> 
// ✅ p className=`text-4xl`>>Hellop>  const size = 4; p className=`text-$size>xl`>>Worldp> 

Of course these are not real solutions. A comment can be deleted or the other element using that class name can be modified to use a different class. The solution is to use full Tailwind CSS class names in your code. Do not use partial names along with dynamic values. Use the dynamic value to generate the full class name in your code.

Setting Class Name Dynamically

To set a Tailwind CSS class name dynamically, I will use a Heading component as an example. It’s a React component that accepts a level prop and returns h1-h6 HTML heading element depending on level value. To apply a different text size, you might be tempted to use a dynamic class name like so:

export default function Heading( level, size, children >)   const Heading = `h$level>`;  return (  Heading className=`$size ? 'text-$xl' : 'text-base'>`>>  children>  Heading>  ); > 

But, as determined previously, it won’t work, because Tailwind doesn’t recognize text-$xl as an actual class name from its collection. You need to mention classes that Tailwind recognizes in your code.

export default function Heading( level, size, children >)   const Heading = `h$level>`;  let style;  switch(size)   case 4:  style = 'text-4xl';  break;  case 2:  style = 'text-2xl';  break;  // . other cases  >  return (  Heading className=style>>  children>  Heading>  ); > 

Safelisting Classes

Alternatively, you use safelisting to list all the classes whose styles you want to be compiled, even if these classes are not mentioned in your code. According to Tailwind CSS documentation, safelisting should be used as a last resort. Reach for this solution only if there is no other way to accomplish your goals. Adjust your tailwind.config.cjs file and configure the safelist .

module.exports =   safelist: [  'text-4xl',  'text-2xl',  'text-xl',  'text-base',  ], >; 
module.exports =   safelist: [    pattern: /text-(base|xl|2xl|4xl)/,  >,  ], >; 

Источник

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