SCSS variable class name - css

On my website, I'm constantly doing style="font-size: #ofpx;". However, I was wondering if there's a way to do it with scss so that, when I declare a class, it would also change the font size. For example:
<div class='col-lg-4 font-20'>whatever here</div>
and this would change my font-size to 20. If I did font-30, it would change my font-size to 30 and etc...
What I have so far:
.font-#{$fontsize} {
font-size: $fontsize;
}

This can't be done for arbitrary sizes. The nature of SCSS is that is needs to be flattened down to CSS before it gets applied to the HTML. What you are asking for, however, is essentially to create rules at run-time rather than compile-time.
In other words, SCSS makes it easier to write some of the repetitive parts of CSS, but it doesn't allow you to do anything new that wasn't already possible with plain old CSS.
What you're asking for is also a code smell. It smells like your markup isn't semantic enough. The purpose of a CSS class is to group objects with similar characteristics, but you're using them instead to describe the styles they impart. I would suggest stepping back and reconsidering what it is that you really want.
You obviously have details of certain elements that are context-dependent. For example, maybe you are applying these rules to buttons when you want to make them smaller or larger than usual. You need to identify the scenarios in which the buttons change. Maybe they are 20% smaller if they are in a modal dialog? Then write your normal .button rules, and also create rules for .modal .button which make it smaller.
If you're positive that you want to define font-size for each element within the HTML (and sometimes there are good reasons for doing so), just continue using inline styles. The only reason inline styling is frowned upon is because it combines model and view logic in a way that harms reusability; however, what you are requesting does so in exactly the same way. This is what inline styles were made for. Don't re-invent the wheel.
With all of that said, you can use sass loops to automatically generate classes for integers within a range. For example:
/* warning: this is generally a bad idea */
#for $i from 1 through 100 {
.font-#{$i} {
font-size: #{$i}px;
}
}
This is not a good idea. Pragmatically speaking it doesn't offer any advantages over just using inline styles and with large ranges your resulting file will be larger (which affects website load times).
Aside: There is a CSS philosophy (or fad, if you're feeling ungenerous) called Atomic CSS (or sometimes Functional CSS) which defies the classical advice given in this answer. I won't give an opinion on its effectiveness at producing clean, maintainable code, but it does typically require more tooling than SCSS alone if used with the degree of specificity requested in this question.

Just going to add, mixins are great, but if you want a util class (attach a class to an element, get that font-size applied to it, do a for-loop in SCSS like so..
#for $i from 1 through 4 {
$fontsize: 10px * $i;
.font-#{$i} {
font-size: $fontsize;
}
}
compiles to
.font-1 {
font-size: 10px;
}
.font-2 {
font-size: 20px;
}
.font-3 {
font-size: 30px;
}
.font-4 {
font-size: 40px;
}
If you want the class to match the # of pixels...
#for $i from 1 through 4 {
$base: 10;
$fontsize: $base * $i;
.font-#{$fontsize} {
font-size: $fontsize + 0px;
}
}
Which compiles to
.font-10 {
font-size: 10px;
}
.font-20 {
font-size: 20px;
}
.font-30 {
font-size: 30px;
}
.font-40 {
font-size: 40px;
}
Codepen example.

When using "words" instead of "numbers" for variables, and the word not being at the end of the classname. I could work something out using CSS Attribute selectors ("wildcard selector"). I can iterate over a map object, and use text values to build CSS selectors.
SASS
//map
$colors: (
primary: #121212,
success: #8bcea8
);
//loop
#each $color, $value in $colors {
//can't do this: div.first-class.is-style-#{$color}-component
//can do this:
div.first-class[class*="is-style-#{$color}-component"] {
background-color: $value;
}
}
HTML
<div class="first-class is-style-primary-component"></div>
This will generate a div.myComponent[class*="is-style-primary-component"] selector and so <div class="first-class is-style-primary-component"></div> (.first-class is not required, selector could be div[class*="is-style-#{$color}-component"] or even [class*="is-style-#{$color}-component"] only).
Yet, in some cases of CSS class naming, it could be limited due to the wildcard selector, which is "larger" than a specific class selector rule.

Of course, inline style tags are bad form. So yes, you should add some classes for font size, or just set font size on the elements you need to as you go. Up to you. If you want, you could use a mixin like so:
#mixin font-size($size) {
font-size: $size;
}
.some-div { #include font-size(10px); }
But that's probably overkill unless you get a group of rules that usually go together.

Just for those of you who might stumble across this question in a more recent time and are new to FrontEnd Development.
What Woodrow Barlow said about using inline-styles instead of rule specific classes isn't quite an up-to-date opinion. For instance, Bootstrap has some of those and Tachyons is entirely built upon them. Actually this practice is called Atomic CSS or Functional CSS.
It's better explained by John Polacek in his CSS Tricks article:
https://css-tricks.com/lets-define-exactly-atomic-css/

You can use mixins like this
#mixin font($fontsize) {
font-size: $fontsize;
}
.box {
#include font(10px);
}

Related

Dynamic CSS class [duplicate]

It is possible to pass parameters for CSS in class name? For example:
.mrg-t-X {
margin-top: Xpx;
}
<span class="mrg-t-10">Test</span>
In this example X should be 10.
No it isn't. The closest we have to this is the attr() function, but that only works within the content property:
figure::before {
content: attr(data-before) ', ';
}
figure::after {
content: attr(data-after) '!';
}
<figure data-before="Hello" data-after="world"></figure>
Perhaps one day this will be expanded so that we can use it elsewhere, but for now this isn't possible.
Currently as I'm sure you're aware if you want to be able to use the .mrg-t-X class, you'll need to define separate style rules for each X you wish to allow:
.mrg-t-1 { ... }
.mrg-t-2 { ... }
.mrg-t-3 { ... }
...
Nowdays you can use CSS variable inside a style attribute instead generating a specific class:
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);).
Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. Custom properties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts.
Custom properties are subject to the cascade and inherit their value from their parent.
example
span {
display: block;
margin-top: var(--m-t);
}
html {
background: repeating-linear-gradient(to bottom, transparent, 10px, lightgrey 10px, lightgrey 20px);} /* see 10px steps */
<span style="--m-t:50px">one</span>
<span style="--m-t:85px">two</span>
<span style="--m-t:110px;">three</span>
Maybe you are looking for SCSS or LESS. It have mixins, variables, etc, and it autocompile real and long css. It was maded to this purposes and write less and less css with the same result.
http://sass-lang.com/guide
http://lesscss.org/
#size: 10px;
.class { font-size: #size; }
Good luck!
It isn't possible to directly pass parameters using just CSS but you're not the first person to ask - check out this question which looks at CSS and JavaScript options and also this might be helpful regarding attribute selection.
This will only help if you are looking at a few variables of margin-top but I don't know what context you're using this in. Depending on what you're using it for there might be better ways.
The simplest way would probably be just to add the style inline to your span <span style="margin-top:10px"> but I try to stay away from inline CSS!
no your code is wrong
but you can write css inside the tag
*<span style="margin-top:Xpx;">*

Use CSS wildcard as a parameter [duplicate]

It is possible to pass parameters for CSS in class name? For example:
.mrg-t-X {
margin-top: Xpx;
}
<span class="mrg-t-10">Test</span>
In this example X should be 10.
No it isn't. The closest we have to this is the attr() function, but that only works within the content property:
figure::before {
content: attr(data-before) ', ';
}
figure::after {
content: attr(data-after) '!';
}
<figure data-before="Hello" data-after="world"></figure>
Perhaps one day this will be expanded so that we can use it elsewhere, but for now this isn't possible.
Currently as I'm sure you're aware if you want to be able to use the .mrg-t-X class, you'll need to define separate style rules for each X you wish to allow:
.mrg-t-1 { ... }
.mrg-t-2 { ... }
.mrg-t-3 { ... }
...
Nowdays you can use CSS variable inside a style attribute instead generating a specific class:
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);).
Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. Custom properties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts.
Custom properties are subject to the cascade and inherit their value from their parent.
example
span {
display: block;
margin-top: var(--m-t);
}
html {
background: repeating-linear-gradient(to bottom, transparent, 10px, lightgrey 10px, lightgrey 20px);} /* see 10px steps */
<span style="--m-t:50px">one</span>
<span style="--m-t:85px">two</span>
<span style="--m-t:110px;">three</span>
Maybe you are looking for SCSS or LESS. It have mixins, variables, etc, and it autocompile real and long css. It was maded to this purposes and write less and less css with the same result.
http://sass-lang.com/guide
http://lesscss.org/
#size: 10px;
.class { font-size: #size; }
Good luck!
It isn't possible to directly pass parameters using just CSS but you're not the first person to ask - check out this question which looks at CSS and JavaScript options and also this might be helpful regarding attribute selection.
This will only help if you are looking at a few variables of margin-top but I don't know what context you're using this in. Depending on what you're using it for there might be better ways.
The simplest way would probably be just to add the style inline to your span <span style="margin-top:10px"> but I try to stay away from inline CSS!
no your code is wrong
but you can write css inside the tag
*<span style="margin-top:Xpx;">*

CSS Set dynamic value depend on class [duplicate]

It is possible to pass parameters for CSS in class name? For example:
.mrg-t-X {
margin-top: Xpx;
}
<span class="mrg-t-10">Test</span>
In this example X should be 10.
No it isn't. The closest we have to this is the attr() function, but that only works within the content property:
figure::before {
content: attr(data-before) ', ';
}
figure::after {
content: attr(data-after) '!';
}
<figure data-before="Hello" data-after="world"></figure>
Perhaps one day this will be expanded so that we can use it elsewhere, but for now this isn't possible.
Currently as I'm sure you're aware if you want to be able to use the .mrg-t-X class, you'll need to define separate style rules for each X you wish to allow:
.mrg-t-1 { ... }
.mrg-t-2 { ... }
.mrg-t-3 { ... }
...
Nowdays you can use CSS variable inside a style attribute instead generating a specific class:
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);).
Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. Custom properties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts.
Custom properties are subject to the cascade and inherit their value from their parent.
example
span {
display: block;
margin-top: var(--m-t);
}
html {
background: repeating-linear-gradient(to bottom, transparent, 10px, lightgrey 10px, lightgrey 20px);} /* see 10px steps */
<span style="--m-t:50px">one</span>
<span style="--m-t:85px">two</span>
<span style="--m-t:110px;">three</span>
Maybe you are looking for SCSS or LESS. It have mixins, variables, etc, and it autocompile real and long css. It was maded to this purposes and write less and less css with the same result.
http://sass-lang.com/guide
http://lesscss.org/
#size: 10px;
.class { font-size: #size; }
Good luck!
It isn't possible to directly pass parameters using just CSS but you're not the first person to ask - check out this question which looks at CSS and JavaScript options and also this might be helpful regarding attribute selection.
This will only help if you are looking at a few variables of margin-top but I don't know what context you're using this in. Depending on what you're using it for there might be better ways.
The simplest way would probably be just to add the style inline to your span <span style="margin-top:10px"> but I try to stay away from inline CSS!
no your code is wrong
but you can write css inside the tag
*<span style="margin-top:Xpx;">*

CSS property value from class name

It is possible to pass parameters for CSS in class name? For example:
.mrg-t-X {
margin-top: Xpx;
}
<span class="mrg-t-10">Test</span>
In this example X should be 10.
No it isn't. The closest we have to this is the attr() function, but that only works within the content property:
figure::before {
content: attr(data-before) ', ';
}
figure::after {
content: attr(data-after) '!';
}
<figure data-before="Hello" data-after="world"></figure>
Perhaps one day this will be expanded so that we can use it elsewhere, but for now this isn't possible.
Currently as I'm sure you're aware if you want to be able to use the .mrg-t-X class, you'll need to define separate style rules for each X you wish to allow:
.mrg-t-1 { ... }
.mrg-t-2 { ... }
.mrg-t-3 { ... }
...
Nowdays you can use CSS variable inside a style attribute instead generating a specific class:
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);).
Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. Custom properties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts.
Custom properties are subject to the cascade and inherit their value from their parent.
example
span {
display: block;
margin-top: var(--m-t);
}
html {
background: repeating-linear-gradient(to bottom, transparent, 10px, lightgrey 10px, lightgrey 20px);} /* see 10px steps */
<span style="--m-t:50px">one</span>
<span style="--m-t:85px">two</span>
<span style="--m-t:110px;">three</span>
Maybe you are looking for SCSS or LESS. It have mixins, variables, etc, and it autocompile real and long css. It was maded to this purposes and write less and less css with the same result.
http://sass-lang.com/guide
http://lesscss.org/
#size: 10px;
.class { font-size: #size; }
Good luck!
It isn't possible to directly pass parameters using just CSS but you're not the first person to ask - check out this question which looks at CSS and JavaScript options and also this might be helpful regarding attribute selection.
This will only help if you are looking at a few variables of margin-top but I don't know what context you're using this in. Depending on what you're using it for there might be better ways.
The simplest way would probably be just to add the style inline to your span <span style="margin-top:10px"> but I try to stay away from inline CSS!
no your code is wrong
but you can write css inside the tag
*<span style="margin-top:Xpx;">*

Make LESS remove useless IDs when compiling

One feature I really love with LESS is nested rules. It makes the stylesheet much cleaner that way and you can find an element very quickly.
I was wondering if there's an option when compiling to optimize selectors. For example...
#global {
/* Styles here maybe */
.container {
/* Styles here maybe */
#sidebar {
/* Styles here maybe */
.title {
font-weight: bold;
}
}
}
}
will be compiled to #global .container #sidebar .title { font-weight: bold; }.
But the first two selectors are useless, since #sidebar should be unique in my page.
Is there a way to ask LESS to compile this to #sidebar .title { font-weight: bold; } instead?
Your assumption is wrong that multiple IDs in CSS are redundant. Imagine, as an example, a site where the CMS generates the page type into the output, like that it's the contact page:
<body id="contact">
<section id="content">Blah</section>
</body>
According to your logic, the following piece of CSS would be a candidate for 'optimization':
#contact #content {
background:red;
}
Now however, your home page has <body id="home"> of course in this imaginary CMS. And suddenly the content of your homepage has a red background because you decided to erroneously optimize that #contact selector out of the CSS, while it most certainly shouldn't have a red background according to this rule.
So no, LESS cannot do this because it would break code. If you don't want the selectors, don't use them and don't put them in your code.
Other answers, including the accepted one, have explained convincingly why LESS cannot simplify your nested selectors in the way you want.
Actually, SASS has the ability to do this:
#global {
.container {
#at-root #sidebar {
.title {
font-weight: bold;
The #at-root directive essentially ignores all the higher nesting selectors. I don't know if LESS has something similar. The above compiles into simply
#sidebar {
.title {
font-weight: bold;
But there is a deeper issue here, starting with the fact that you "love" nested rules in LESS. Stop loving them quite so much. I don't know about you, but most people love nested rules because they think it's cool to exactly mimic the hierarchical structure of their HTML. The SASS docs even claim this as a benefit:
Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML.
So people with HTML such as
<div class="foo">
<ul>
<li class="item">
write LESS like
.foo {
ul {
li.item {
This is a horrible, horrible idea, It makes the structure of CSS completely dependent on the structure of the HTML. If you change one nesting level in the HTML, your CSS breaks. Often this approach is combined with a lot of rules defined against tag names such as ul instead of class names, which aggravates the dependency, so changing the ul to ol in the HTML breaks the rules again. Or it's combined with rules based on Bootstrap classes such as col-md-6, so if you ever change that to col-md-4 things break again.
CSS rules should be orthogonal to the HTML. They represent a different dimension. They represent styling concepts which are applied selectively throughout and across the HTML.
I am guessing that you wrote
#global {
.container {
#sidebar {
.title {
font-weight: bold;
because you are adopting this mistaken idea of mirroring the HTML structure in your LESS. Then, you notice that this compiles down to having selectors which contain multiple IDs, which you imagine must be inefficient (although, actually, the degree of inefficiency is minimal). You yourself are writing extraneous nesting levels in your LESS, then complaining that they may be slowing down performance!
Worse, you've hard-wired assumptions about the HTML structure into your CSS. It's of no consequence that the sidebar happens to fall inside a .container which is inside a global element. So don't write them. Perhaps at some point you decide to change the container class to container-fluid. Boom, instantly your CSS breaks. What is the point of conditionalizing the fact that the title should be bold on it being contained with a container class, which in any case is a layout-related class that has (or should have) nothing to do with styling? If you're going to duplicate your HTML structure in your CSS using preprocessor nesting, just go back to writing inline styles. At least that way you'll only have one file to change when you change your HTML around.
When designing CSS, you should think just as hard about the design of the rules as you do about the design of classes and methods when writing JS. In this case, you need to ask yourself, "What characterizes the situation where I want some title to be bold? What drives that? What is the nature of boldness? What am I indicating by boldness? What is the semantic notion indicated by boldness?"
Let's say that you want all titles to be bold. Then you simply say that:
.title { font-weight: bold }
Let's say that you want a title to be bold only when it's in the sidebar. Then you simply say that:
#sidebar .title { font-weight: bold; }
My suggestion here is to go cold turkey. Stop using nesting during a withdrawal period. Write rules with the minimum number of selector components. Refactor your classes to have semantic names (such as title-emphasis). Once you're "sober", you can go back to cautiously using LESS's nesting capability when it is useful, such as perhaps for hover:
#boo {
color: red;
&:hover {
color: blue;
}
}
This is actually useful and saves you from writing #boo twice, and groups the rules in an easy-to-understand way.

Resources