Do CSS functions exist? - css

I'm not sure what to call this, but basically let's say I have a style that I use a lot,
.somepattern{
font-size:16px;
font-weight:bold;
border:2px solid red;
}
but sometime I want to change the font-size and the color for border. Is it possible to treat this code as a library, where I can set the style to a div
<div class="somepattern">Text</div>
but still control the 16px and red like we do with functions?

I know I'm late to the party but the selected answer IS NOT the right answer since it's deferring it to CSS preprocessors.
To answer the specific question "Do CSS functions exist?", the answer is: Yes.
However, CSS functions work completely different than the OP's concept initially is.
cuixiping's answer seems the most correct answer.
Examples of CSS functions are:
url()
attr()
calc()
rotate()
scale()
linear-gradient()
sepia()
grayscale()
translate()
A detailed, comprehensive list can be found here:
CSS functions on MDN Updated link 18/9/20

You can't programatically control CSS from your markup, but you can use one of the many CSS extensions to make CSS work more like a compiled language.
http://lesscss.org/
http://sass-lang.com/
If we wrote your example in LESS, we'd get something like this:
.somepattern(#color: red, #size: 16px) {
font-size:#size;
font-weight:bold;
border:2px solid #color;
}
And then you could use it in your LESS file like so:
.myclass {
.somepattern(green, 20px);
}

Nope. No CSS functionality like you require. At least not directly.
But there are at least two rather generic ways for you to use to accomplish what you need:
Class combining
You can of course combine as many classes as you like in any element like:
<div class="heading run-in">
Some heading
</div>
Lorem ipsum dolor sit amet...
and you'd have CSS defined as:
.heading {
color: #999;
font-size: 16pt;
font-weight: bold;
border-bottom: 2px solid red;
display: block;
margin: 1.5em 0 .5em;
}
.run-in {
display: inline;
margin: 0;
font-size: 1em;
}
LESS CSS
And there is of course LESS CSS project that lets you define variables (and has other sugars as well) and use them in other classes.
LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. LESS runs on both the client-side (IE 6+, Webkit, Firefox) and server-side, with Node.js.
If your server platform is .net there's a project DotLessCSS with a library in .net as well. And there's also T4 template by Phil Haack.
Mind that there are many CSS preprocessors/enhancers like LESS CSS as well:
SASS
xCSS
HSS
CleverCSS
And probably some others that I didn't mention. Some support nesting CSS3 selectors as well others don't. Some are aimed at particular server-side technology some don't. So choose wisely.

you can redefine style by adding the style tag to your HTML:
<div class="somepattern" style="font-size:5px">Text</div>
or by applying multiple classes like class="somepattern small".
HTML
<div class="somepattern small"> Text </div>
CSS
.small {
font-size:5px;
}
the small class will be applied after the somepattern class and will therefore override any properties set in the some pattern class.

Even later to the party!
You can now do this with css custom variables.
In our css using the var() function:
.some-pattern {
font-size: var(--font-size);
font-weight: bold;
border: var(--border);
}
Then in our html defining the custom variables inline:
<div
class="some-pattern"
style="--border: 3px double red; --font-size: 16px;"
>
test
</div>

What you described is actually done with style attribute.
<div class="somepattern" style="font-size:10px;">Text</div>
I think this is exactly what you want. And it is not recommended, because it breaks the usual (good) pattern of spitting content and its visual style. (Although, honestly, I do use it a lot. ;-))

its a css class. It cannot be used like functions if that's what you are asking. There is no code library as its not a compiled. CSS is just presentation semantics (formatting) of a document written in a markup language. You can include all css classes in a .css file and use it where ever you want instead.

I've come to realize through the comments of others that this solution overcomplicates the problem at hand. This solution works but there are easier and better alternatives that do not depend on server-side scripting.
You can actually control your stylesheet if you make it a php file stylesheet.php?fontsize=16 and then inside your stylesheet you can retrieve the variable
<?php
header("Content-type: text/css");
$fontsize=16;
?>
.somepattern{
font-size: $fontsize;
font-weight:bold;
border:2px solid red;
}

Yes, it's possible. But you have to make it on your own with the help of Recatjs(u don't have to go deeper, basic is enough for this). Actually, think like that If bootstrap can make such things where we just have to define the class name and it automatically designes HTML files, then why we cannot do it.
Here's the image of my code(https://i.stack.imgur.com/hyePO.png)
and this is how I used it in my jsx code (https://i.stack.imgur.com/yK6VD.jpg)

Do you mean inline styles ? <div class="somepattern" style="border-color:green">Text</div>

Related

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.

increment an html element's attribute value using css?

Would it be possible to create a css class/id that would add a value(say, padding for example) to another class's same attrib value?
Let me try to put it down more clearly.
.someClass{
padding: 20px;
}
.thickenMe{
padding: 5px;
}
And when i apply these classes as follows,
<div class='someClass thickenMe'>
<!--planning to beef up this div-->
</div>
This div's net padding should become 25px.
Would it be possible using css only? Its just a thought!
This is not possible using pure CSS.
You could, however, write a CSS clause for each element that can be "thickened" like so:
.someClass{
padding: 20px;
}
.someClass.thickenMe{
padding: 25px;
}
Another alternative would be to use margin as well as padding, like so:
.someClass{
padding: 20px;
}
.thickenMe{
margin: 5px;
}
That might not be possible though, depending on your other CSS.
The easiest solution, although not pure CSS, would be to use JavaScript. Here is an example using JQuery:
var prevPad = $('.thickenMe').css('padding').replace("px", "");
prevPad = parseInt(prevPad);
$('.thickenMe').css('padding', prevPad + 5 + "px");​
No. You need to use client-side scripting (i.e. JavaScript) if you want to change attributes dynamically. Or, if you just want to define styles by compiling from some dynamic sources, try LESS or SASS.
Unfortunately, no. You could get this sort of functionality by using a CSS-processor like LESS, which gives you variables, or you could handle it through client-side scripting (easiest with jQuery), but native CSS simply doesn't work that way. Classes override each other when they specify the same attribute; they don't supplement each other.

With CSS, how to style a generic, global style?

Update: this question is about global style. So solution such as #some-id .score is NOT a solution.
At first, I was styling as
.score { font-size: 32px; color: #777 }
And the "score" is something that can happen any where, something of a global style. But since other style actually might have:
#summary-panel { font-size: 13px }
The one with id will override the one just having classes (the first CSS rule in this post). (So if score is displayed within summary-panel then the font-size will be overridden to be 13px but the score style is supposed to be global and need a 32px style.) So I was tempted to use
.score { font-size: 32px !important; color: #777 !important }
because the !important can act as the "second level" which override everything ordinary, and act as a global style.
Is this a good way or better way? One catch is that if sometimes we might have a CSS issue with IE 7 (or IE 6), that we need a separate stylesheet such as ie.css, and in there, there might be also
#summary-panel { font-size: 12px !important }
so in this case, the !important will be overridden because the one having an id will always win over just classes. So is there a better way?
Maybe this?
#summary-panel.score { font-size: 32px; }
I guess I'm not sure how many styles you want to add or if the question is how to do this without adding any new styles, in which case I'd say there is not a better way.
This is where you use span.
For example the markup:
<div id="sometext">
<p>Lorem ipsum <span class="score">test</span> dolor sit amet</p>
</div>
And the CSS:
div#sometext {
font-size: 12px;
color: yellow;
}
span.score {
font-size: 42px;
color: green;
}
this question is about global style.
So solution such as #some-id .score
is NOT a solution
[...]
.score is NOT a solution So is there a better way?
there is no answer, all the comments you got in the first answer are valid and polite, but I would tell you as a user, that you should not use !important unless in an emergency to override external code that is outwith your control, !important is for user styles
CSS is a mindset, a suggestion, your request (with a please ;) to the browsers how you would like your styles displayed - at the minute you seem to be struggling between the mindsets
The logical programmer side wants a "global" style, and I believe most programming languages have "globals" ? CSS is not a programming language it's a markup language.
Anyway, the recent last 3-4 years CSS'ers have been encouraged to "class everything" YUI and Blueprint and other frameworks would have us do so.. but that means you should not use ID's because as you rightly point out they override.. they are the ultimate in the CSS Specificity Wars.. BUT as an efficient CSS coder you need to use ID's - that is best practice isn't it? - so if you do need to mix them then you should group your ID selectors and if necessary group the class selectors as was suggested to you
there really is no answer here (except there no such thing as global styling unless you pass it down via ID's and inheritance, it's a coding preference rather than a right/wrong answer

Using OR in CSS selectors

I have an element which appears on many pages and I would like to style it differently based on the class of the high-level div which it is present in. For example, if I want to change the color of my logo depending on the "type" of page it is present on. Then let's say these types can be grouped (so typeA, typeB and typeC should use one color while typeD and typeE should use another). Also, as high-level div's these types are used for other things as well so they cannot be merged.
.typeA #logo,
.typeB #logo,
.typeC #logo{
color: #ffffff;
}
.typeD #logo,
.typeE #logo,{
color: #000000;
}
Is there a way to chain together with some selector so that I don't have to make this code look so nasty. This example is small but the real-world version involves a whole lot more types. Is there a way to do something like:
.typeA || .typeB || .typeC #logo{
color: #ffffff;
}
As others said, CSS doesn't support that kind of grouping.
If you have control over your markup, why not just add a common class to each group of type classes then select that common class?
Example:
<div class="typeA type1">
<span id="logo">Site Title</span>
</div>
<div class="typeD type2">
<span id="logo">Site Title</span>
</div>
.type1 #logo { color: #ffffff; }
.type2 #logo { color: #000000; }
In short: no.
There are systems like LESS which make this possible but the rendered css will still look like your first example
Sorry, not in straight CSS, no. There are projects like http://sass-lang.com/ that require an external compiler to do what you want, however.
This isn't possible with pure CSS. It can be done however with a meta language like SASS. Check out http://sass-lang.com/ for more information.
There is no "or" in css that i know of. Just use a different selector that is a parent of typeA,B and C like "containerA" or "containerB"

Can I join 2+ styles together into a superstyle?

I was looking to join 2 styles together to make a super style for easy use and customisation of my page.
Is it possible to define something like this? (if so how)
.bold { font-weight: bold;}
.color1 {color: white;}
.boldColor {.bold; .color1;}
where .boldColor is effectively
.boldColor {font-weight:bold; color:white;}
I want this so that I can have styles thoughout the page and be able to easily change the colors in many places in 1 place. I'm currently using <p class="bold color"> but some of my class defs are becoming long so I'd like to be able to use <p class="boldColor">
Thanks
You can't do exactly what you are asking for but you can get similar effects by using a comma to separate multiple css selectors that share the same properties.
.bold, .boldColor {
font-weight: bold;
}
.color1, .boldColor {
color: white;
}
This way class="boldColor" will have the same effect as class="color1 bold".
This is not possible using normal CSS. You would usually do this, as you already say, by combining class names: bold color
There are CSS "pre-compilers" that can do advanced things on CSS stylesheets, like working with variables. I don't know of any that does "class fusions" like you request but I'm sure they can be helpful in reducing code size. Check out LESS and xCSS, for example.
No, the CSS spec does not support this.
No you cannot do this. How you are doing it currently is ideal.
Check out LessCss (.NET version)

Resources