Using Scss variables with multiple styles? - css

I'm getting into scss and have been trying to apply most of my styles through variables.
There is certain variables that I want with multiple styles. For example something related to fonts.
I want all 12px size fonts to be red.
I declared a variable like
$font-12: (font-size: 12x, color: red)
Obviously I can't apply this variable like normal ones since it includes multiple styles.
Is this the correct way to declare a variable like this?
Can I even apply this variable like this?
If not, what is the correct way to apply related styles using scss?
Thanks.

You can do this via mixins.
#mixin font-12(){
font-size: 12px;
color: red;
}
Documentation: https://sass-lang.com/guide
However you can also do this in native CSS.
Simply create a utility class (this is a normal css class, I call it a utility class because it's reusable):
.font-12 {
font-size: 12px;
color: red;
}
And apply this class to any elements you want IE:
<div class="card font-12"> ..some card... </div>
<h3 class="card-title font-12"> .. some card title.. </h3>

I'm sorry, I would have liked to comment alex067's answer but as I'm not very active here my reputation would not suffice to comment therefore I have to post it as an answer:
Using a mixin is exactly the correct answer.
BUT: I strongly advise against the second proposed option!
While is is technically correct, doing it that way defeats the whole purposes of using CSS in the first instance. We could more or less go back to using old-style font-color tags etc. if we would go about it this way.
CSS is made to abstract content/semantics from design for a host of very good reasons. If you want to go the pure CSS way (no SASS) at least name your style something like 'unimportant' or 'by-line' so that it could make sense when you redefine it for different screens, high-contrast schemes, screen-reader output etc.
[With Bootstap and all those other bloody frameworks out there it seems that nobody cares about clear accessible structure and using stuff the right way; and my struggle for doing things the intended way may be futile - still I feel the need to fight for it.]

Related

CSS: overriding specific selectors with a more general one

I have a CSS stylesheet that specifies the font for each paragraph class:
p.body {
font-family: Tahoma;
/* (more properties omitted for brevity) */
}
p.bodytextcenter {
font-family: Tahoma;
}
p.bodytextright {
font-family: Tahoma;
}
(etc. for dozens of styles).
Now I have to use a different font for some languages. I can do this by making a new selector p.body[lang="de"] etc, but I'd have to do that for every style in my list.
Is there a way to specify p[lang="de"] and have it apply to all paragraphs with that language attribute? Or would this require me to remove the font-family attribute from every paragraph class?
p[lang="de"] this may work but if not you can add !important on the font family style
Give this a try:
html body p[lang=de]
...or similar, depending on your actual HTML. You just need to add more levels of specificity.
This can't properly be answered without seeing your HTML; but I'm going to guess that the CSS is poorly structured, and that's what's making this hard for you. Doing the above is slightly hackish, but syntactically legit.
The rest of this might not help so much now, but good to keep in mind for the next project....
It's best to design your page structure based on the semantic meaning rather than the specific effect. Navigation, article, aside, sidebar; not left, right, bold, etc. Imagine you have a sidebar on the right. You could name it "sidebar" or "textright". But down the road you decide to put it on the left.... or do something completely different on mobile. Now "textright" is just mislabelled.
Even keeping with your current way of doing it, you should note that an element can have multiple classes. So rather than having:
<p class="body">...</p>
<p class="bodytextcenter">...</p>
<p class="bodytextright">...</p>
you could have something like:
<p class="body">...</p>
<p class="body textcenter">...</p>
<p class="body textright">...</p>
With that you can set fonts on p.body, and layout on p.textcenter and p.textright
That's an imperfect answer for the current project, as it would require changing a lot of existing text, but that goes back to the initial issue -- poorly structured CSS. (And again, without seeing HTML I'm mostly guessing here....)

css styling using custom attributes to make it more readable. good or bad?

I have some css styles with background colors, borders, etc... like this:
.bg-red {
background-color:red;
}
.bg-blue {
background-color:blue;
}
/*more background colors*/
.border-red {
background-color:red;
}
.border-blue {
background-color:blue;
}
/*more border colors*/
/*Like this i also have foreground color, border thickness, border style, transition/hover styles (specially for button hover) */
Like this i can style for example buttons.
example
<button class="fg-green bg-white
border-color-red border-thickness-thick border-style-dashed
hover-bg-grey hover-fg-black
hover-border-blue">
</button>
To make this more readable and shorter, i want to change it to this using custom attributes and css3 selectors
<button color="fg-green bg-white"
border="red thick dashed"
hover-color="bg-grey fg-black"
hover-border="blue">
</button>
but is this good practice?
I've read a lot of questions about this, and i can't really decide what i should do.
1) Is it OK to add your own attributes to HTML elements?
and a lot of other questions
From this question, i learned that custom attributes are not W3C compliant. but that html5 allows you to create custom attributes using the data- prefix.
in my opinion, colors and borders are not really data (or are they?), and the prefix is mostly used for javascript. so i don't know if i should do this.
2)
Is it a bad practice to use custom HTML attributes and style them with CSS?
Here, i read that classes are better, but should i give up readability and use classes instead?
So, what is more important? Making the code more readable by using attributes, or using classes but making it less readable?
Or is there a better solution?
Suggestions are always welcome!
edit: i'm just a beginner, so i don't know much about what's good and what's bad practice...
EDIT AGAIN: Thank you all for this info, all the answers where usefull so i upvoted every single one.
Also thank you Alochi for your helpful comments.
This is not a good practice.
How to use custom attributes?
First, you should use data attributes instead of full-custom attributes:
<button data-color="fg-green bg-white"
data-border="red thick dashed"
data-hover-color="bg-grey fg-black"
data-hover-border="blue">
</button>
These are syntaxically valid, and you can use as many as you want. Keep in mind they shouldn't interfere with external libraries (which are also allowed to create their own data attributes).
Is Object Oriented CSS the solution?
What you're doing is called Object Oriented CSS, and was popularized by frameworks like Bootstrap (formerly Twitter Bootstrap).
You've started to strongly link your HTML to your CSS.
Content is no longer independent from layout!
Sure, you've got less work to maintain your CSS, but:
this work is deported on your HTML
your HTML is dependent from your CSS
your HTML is not semantic
If you want to use CSS, you should think to reduce your amount of classes, and use semantic classes instead, like this for example:
.button-valid {
color: white;
background-color: green;
border: 1px solid green;
border-radius: 5px;
transition: all .2s;
}
.button-valid:hover {
color: green;
background-color: white;
}
Using <button class="button-valid"> has far more meaning than <button class="bg-green fg-white radius-5 b-green bgh-white fgh-green">
From CSS to Sass, and from OOCSS to OOSCSS?
So far, the better solution is to start to use CSS preprocessors.
I you want to go further, I would suggest you to read articles about Sass and OOSCSS.
First of: There was never an exclusive list of allowed tags and attributes, except in XHTML (dtds!) for validation. HTML itself is meant to support custom data structure. I know, there are a lot of people out there, disagreeing with 'if it is not restricted, you may use it'.
Best practice? Well, separating data and style is the rule of thumb. Classes are 'backwards compatible', custom tags in HTML (btw: HTML5-CustomComponents) too. But not attributes used in selectors (please search for a suiting CSS reference yourself).
Adding custom attributes per se is not bad. But there is a general agreement on prefixing custom attributes (HTML5) with data- e.g. data-my-custom-attr="abc". In CSS3, this is used as [data-my-custom-attr] {} or [data-my-custom-attr="abc"] {} to be accessed.
jQuery for example, makes these data attributes natively accessible by their $(elem).data() command, e.g. var val = $(elem).data('my-custom-attr');
This is primarily opinion based but...
Is it OK to add your own attributes to HTML elements?
Can you do it? Yes. Should you do it? Probably not. Why? Well, there are a number of reasons but from the top of my head...
Your code becomes less future proof. For instance, if a future HTML spec decides to introduce a new attribute that clash with yours. This can be overcome with data-prefixed attributes or using XHTML with a custom schema but...
Your code becomes less reliable. Since it does no longer adhere to the W3C spec, results might be inconsistent between browsers. Making a website with a consistent look between browser's versions is hard enough as it is...
Even using data prefixed attributes, it might not improve readability like you claim, specially for others or even a "future you". You might forget what an attribute means and, well, it becomes hard to find it's meaning unless you extensively document your system for future reference.
Also, for readability sake alone, I personally find this equally readable
<button class="fg-green
bg-white
border-color-red
border-thickness-thick
border-style-dashed
hover-bg-grey
hover-fg-black
hover-border-blue">
</button>
Is it a bad practice to use custom HTML attributes and style them with
CSS?
Well, it kind of defeats the purpose of CSS, whose idea is separation of style and content. Your system is not so different than in-line styling. <div style="color: red;"></div>. Why is this separation important? Because if you wish to change the styling later, it becomes a lot harder. You will need to run through your entire html files changing each instance, instead of changing it in your CSS.

Priorizing CSS properties

I am building websites for a while, and I have a question about CSS I can't really rid over. So there is that frequent situation when multiple classes affect a DOM element, and both classes declare the same properties. For example:
.first {
color:white;
}
.second {
color:black;
}
I know that if I have an element with class="first second" in that the text will be black. If I rather want it to be white, I have several options:
Using !important: I know this one is handy and I use it, but sometimes, if I use it too often, my CSS may become messy. I mean, multiple !important's can result the same basic situation.
Reordering the classes inline: if I am correct, which class comes first, it will be the priority one. This is nice, but i often work with environments where I can't affect that. Secondly, this is not a global but a local solution.
Reorder the CSS itself: well, this sounds interesting, but if I work with many stylesheets (and I do), it is hard to track, especially when it is WIP.
Actually what I am looking for is some workaround like z-index but for priorizing which class is stronger. Because I can't really find anything useful in this topic, I am just curious maybe it is a user error, and you guys know something I don't. How do you manage this? What do you suggest?
class="first second" is the same as class="second first". The priority is based on the position of the declarations in your css and not in their position on the html element.
So, if you want priority of a class against another, put the top priority class LAST on the css file.
.first {
color:white;
}
.second {
color:black;
}
in this example, class second has always priority over class first. This happens because browser scans through the css top-to-bottom and always applying the rules of matched classes that finds. So, the last matched class has priority over the previous matched classes.
see this fiddle: http://jsfiddle.net/5c29dzrr/
At the same specificity level, the CSS selector that is furthest down the stylesheet will be applied. So in your example, if you wanted in that situation to have the element with the white colour you would have to order your properties like so:
.second {
color: black;
}
.first {
color: white;
}
The order of the classes in the HTML tag is not important; it is the order in which they appear in your CSS.
The better way to handle this is to go with some better naming convention such as BEM or SMACSS so that you don't have the issue of conflicting class names.
Edit: It might be worth reading up on specificity and the cascade for a better understanding of this. I found this calculator to be pretty handy in determining which rules will take precendence, although these days you can just use the developer tools to find out that information.

Is there a way to apply a CSS class from within a style?

I'm trying to be more modular in my CSS style sheets and was wondering if there is some feature like an include or apply that allows the author to apply a set of styles dynamically.
Since I am having a hard time wording the question, perhaps an example will make more sense.
Let's say, for example, I have the following CSS:
.red {color:#e00b0b}
#footer a {font-size:0.8em}
h2 {font-size:1.4em; font-weight:bold;}
In my page, let's say that I want both the footer links and h2 elements to use the special red color (there may be other locations I would like to use it as well). Ideally, I would like to do something like the following:
.red {color:#e00b0b}
#footer a {font-size:0.8em; apply-class:".red";}
h2 {font-size:1.4em; font-weight:bold; apply-class:".red";}
To me, this feels "modular" in a way because I can make modifications to the .red class without having to worry so much about where it is used, and other locations can use the styles in that class without worrying about, specifically, what they are.
I understand that I have the following options and have included why, in my fairly inexperienced opinion, they are less-than-perfect:
Add the color property to every element I want to be that color. Not ideal because, if I change the color, I have to update every rule to match the new color.
Add the red class to every element I want to be red. Not ideal because it means that my HTML is dictating presentation.
Create an additional rule that selects every element I want to be red and apply the color property to that. Not ideal because it is harder to find all of the rules that style a specific element, making maintenance more of a challenge
Maybe I'm just being an ass and the following options are the only options and I should stick with them. I'm wondering, however, if the "ideal" (well, my ideal) method exists and, if so, what is the proper syntax?
If it doesn't exist, option 3 above seems like my best bet. However, I would like to get confirmation.
First of all you cannot do apply-class:".red";
to perform this type of action i will suggest you to use this method
.red {color:#e00b0b;}
h2 {font-size:1.4em; font-weight:bold;}
.mymargin{margin:5px;}
<h2 class="red mymargin">This is h2</h2>
and to use in div
<div id="div1" class="red mymargin"></div>
In this case if you will change in .red class.it will be changed everywhere
Short answer: There's no way to do this in pure CSS.
Longer answer: Sass solves this problem via the #extend directive.
.error {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
#extend .error;
border-width: 3px;
}
This lets you keep your CSS modular in development, though it does require a precompilation step before you use it. It works very nicely though.
You can use the DOM in javascript to edit the id and/or class attributes of HTML tags dynamically.
I agree with DarthCaesar and jhonraymos. To update a class using JavaScript, all you would need is a simple:
function toggleColorClass(e){
var redClass = document.getElementsByClassName('red');
redClass.removeAttribute('class', 'red');
/*Set the class to some other color class*/
redClass.setAttribute('class', 'blue');
}
Of course, to make this work, you would need to include the above function in your document somewhere... if this is all the JS you're using you can probably stick it in the head or even use it inline. You would probably also want to write it so that the toggle goes in both directions, i.e. turning red on and off. Furthermore, jhonray's snippet is probably how you would want to mark up your CSS.

What are good 'marker' css styles to define?

I am finding it useful to define 'marker' css styles such as 'hidden' or 'selected' so I can easily mark something as hidden or selected - especially when using a tag based technology like ASP.NET MVC or PHP.
.hidden
{
display:none;
}
.newsItemList li.selected
{
background-color: yellow;
}
I don't especially feel like reinventing the wheel here and wanted to know what other things like this are useful or common - or if there are any pitfalls to watch out for.
Should I look at any specific css frameworks for other things like this? Plus is there a name for this type of css class that I can search by.
I agree with the other posters who say only to define what you need, rather than bloating your code with a bunch of unnecessary classes.
That being said, I find myself using the following on a constant basis:
.accessibility - visually hide elements, but keep them intact for screenreaders and print stylesheets
.clear - tied to Easy Clearing
.first-child and .last-child - easily assign styles to the first/last item in a container. This has been a lifesaver many times, and I prefer it over the poorly-supported :pseudo selectors
.replace - tied to Phark IR for transparent image replacement
Finally, I dynamically assign .js to the <html> element with
<script type="text/javascript">if(h=document.documentElement)h.className+=" js"</script>
This will allow me to define .js (rest of selector) styles to target only browsers with JavaScript enabled.
Let me give you an answer from a very novice web developer who has recently considered using CSS classes as "markers". Please don't take this as a definitive answer, as I may be completely wrong, but look at it as another point of view.
I was going to use some marker classes, too. I created one called .center to center the elements in a DIV tag. However, I was struck with the idea that I'm looking at CSS all wrong. I reasoned that CSS is supposed to define how an element is to be displayed without having to change the HTML page. By using marker classes, like .center for example, I would have to change BOTH the CSS and HTML if I wanted that DIV tag to be right-justified next month. So instead, I created a .latestHeader class (the DIV is to hold the "latest information" such as a news item), and in that class I set the text to align center. Now, when I want to change the justification of the text, I simply change the CSS for that DIV and I don't have to touch the HTML.
In regards to your question about CSS frameworks...
Personally I've always found the W3C has the most complex but also most accurate answer to any CSS question.
After many years of programming and playing around with CSS/HTML/PHP I agree with the above comment.
There is no harm in defining a marker for something to be centered or right-aligned using something along the lines of a '.center' or '.righths', but keep in mind as above that if you want to change a whole slab of text your work will be increased because you have to edit both CSS and HTML.
Defining the format for a whole section will mostly likely work out more logical, because if you want to change the section months down the trail, you just have to edit the format of one CSS declaration as opposed to editing each individual article.
CSS was however designed as the ultimate styling language which could allow an administrator to make a website look exactly what they want it to. Keep in mind though that excess CSS will increase the load on a server, will increase the time before your client sees your page and in line with the 'feng shui of web design' it is possible to go overboard with too much styling.
You should really grow this list on a need basis instead of soliciting a list of generic classes across the board--you'll only end up with bloat. If you want to avoid reinventing the wheel the look into some CSS frameworks (blueprint or 960). In some respect, generic classes like .center { text-align:center } do have some level of redundancy but often times they're needed. For example the following pattern which is all too common but should be avoided:
element.onclick(function(e){ this.style.backgroundColor = 'yellow' }
That's bad because you really ought to be using:
element.onclick(function(e){ this.className = 'highlight' }
The latter allows you to modify your styles by only touching the CSS files. But if a CSS class name has only one style element then you should probably avoid it because it doesn't make any sense to have it (.hidden in your example) and call it directly instead:
element.onclick(function(e){ this.display = 'hidden}
I often find myself keeping two classes in all of my stylesheets: "center" (which simply applies text-align: center;, and a float-clearing class that applies clear:both;.
I've considered adding a "reset" statement to all my styles, but haven't had a need for it yet. The reset statement would be something similar to this:
*
{
margin: 0;
padding: 0;
}
I reuse these often enough to include them in just about everything. They're small enough so I don't feel they bloat the code at all.

Resources