Why CSS does not support function-like constructions? [closed] - css

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am mostly a backend programmer, and am relatively new to CSS. So far, I hate it. My biggest complain is that is incredibly redundant and difficult to produce readable code.
Many times I need to apply styling to different but similar elements. However, I find it incredibly challenging to produce elegant code to do that.
The most simple way to do things in CSS seems to be to give an ID to everything and use custom code for every single element in the page, or classes when there are repeated elements with. However, this still leaves a lot of repeated code, like when I have two elements that are almost exactly alike, but have one or two different attributes, like width, background color, color or float side.
My current solution is defining many atomic classes, like
.bgRed { background-color: red; }
.bgBlue { background-color: blue; }
.fontCenter { text-align:center; }
.left { float: left; }
and so on, and applying multiple classes to an element, like this:
<span class='bgRed left' >My text</span>
But that's still very short of decent. Some attributes, like width and height, are usually strongly tied to it's elements, so I can't create an atomic class for it, and end up resorting to using it's ID.
Finally, my question: Why doesn't CSS support some kind function-like structure? Would a feature like this be useful in CSS? Is CSS badly designed or I just don't know how to use it properly? Why was CSS designed the way it is?
How I imagined functions in css would work:
Defining a css function:
_sidebar(float_side, color, width){
float: float_side;
backgroud-color: color;
width: width:
height: 200px;
color: #FE02A5
list-style: none;
display: table;
}
And applying:
<div cssfunc='sidebar(left, #FF0000, 150px)' >
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
Bonus question: How do you maintain you CSS code readable and organized, with minimal code repetition?

This is not the intended usage pattern for CSS. A general clue is if you have specific formatting words like colors or alignments in your class name, you're not following the "spirit" of CSS.
The intention for CSS classes is to use semantic categories for class names. For example instead of having a class named bgRed, use one called warning. The difference might be subtle in some cases, but the difference in philosophy usually helps maintenance. Instead of combining "literal" css rules at the element level, you'd combine more meaningful semantic ones like class="sidebar warning".
With that said, some people still find the lack of reusability of formatting between CSS rules cumbersome. There are fixes for that as well. The best solution is to use a CSS pre-processor like LESS or SASS. These languages compile into CSS, but support things like mixins and variables that function very much like the css enhancement you have in mind.

HTML defines what to show, CSS defines how to show it. If you use classes like "bgRed" or "left", you are doing this old way.
CSS doesn't define support functions, but LESS does. Imagine this:
.sidebar(#side, #color, #width) {
float: #side;
backgroud-color: #color;
width: #width:
height: 200px;
color: #FE02A5
list-style: none;
display: table;
}
.sidebar-important {
.sidebar(left, red, 100px);
}
.sidebar-misc {
.sidebar(right, blue, 50px);
color: grey; // overwrites .sidebar function
}
Then in HTML:
<div class="sidebar-important">Important news</div>
<div class="sidebar-misc">Something else</div>
This way, you can easily change values in LESS file, compile it to CSS and you won't need to change it in HTML.
Bonus answer:
LESS.

Related

Overwritte Childs Property with CSS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a <div> element inside a <li> element (as shown in code snippet). The <li> element has cursor: pointer style property set and I can't remove the cursor pointer in that nested <div> element.
The <li> is not in our control to remove css, since it comes from a third party.
.container {
cursor: pointer
}
.local {
cursor: default !important
}
<ul>
<li class="container">
<div class="local"> Hello World </div>
</li>
</ul>
The .container class is actually irrelevant here. It just so happens that it has a cursor: pointer property which shows on, but the problem is in fact - What is overriding the .local classed <div> element from rendering the cursor: default property.
The best way to answer that would be to take a look at the elements and styles panels on your browsers developer tools and see what's doing that. It will let you know what's overriding it.
Then you can use adjustments, either by increasing specificity, or by changing the code that's overriding it. But the specificity needs to be relevant in comparison with the .local class and whatever is actually overriding it.
Edit: In the provided example, you don't need to worry about specificity because they're different classes. However, I frequently see !important being added to rules as a lazy way to override specificity issues that aren't replicated in the example. I assume that to be the case here as well since the OP notes that, "the container comes from a third party". So understanding specificity rules will help resolve the issue.
You could use !important but that should really be a last resort. However, you're much better served long term by increasing CSS Specificity.
Currently .container & .local have equal weight. You can increase specificity by: Using an ID, referencing more hierarchy, using combinators etc. Then the NEW attributes will override the previous attributes based on CSS order.
Eg:
.element {
background: blue;
}
.element {
background: red;
}
// produces a red element
So in this case you want to increase specificity. You can do that easily like this:
.container {
cursor: pointer;
}
.container > .local {
cursor: default;
}
// where local is a DIRECT child of .container

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.

LESS - Nesting generates bad CSS code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In the following article I read that one should try reduce the number of selecetors.
Article: use less selectors
I'm wondering if writing LESS and I'm using a lot of nesting to group parent and child elements, will that generate bad CSS code in the end?
LESS
.wrap{
width: 100%;
height: 20%;
background: green;
header{
background: blue;
h1{
color: red;
}
}
}
I'm using a lot of nesting to group parent and child elements, will that generate bad CSS code in the end?
In a word, yes. In the long run this will give you highly specific, unmaintainable CSS. Let 's have a look at what your example will produce for the h1 style.
.wrap header h1{ color: red; }
So what you've ended up with here is a very specific CSS selector, that isn't really necessary. You could, for instance, just have
h1 { color: red; }
or use a class on the h1
.title { color: red; }
Why is specificity bad?
So imagine, 6 months later another developer comes along and they need to change the color of a h1, but just one of them.
First they try to add a class to the h1
.new-color { color: blue; }
But the colour doesn't change because the original CSS is so specific. So they have to do this
.wrap header h1.new-color { color: blue }
or worse still they may do this
.new-color { color: blue!important; }
And then what happens when other changes need to be made? As you can see very quickly and very easily you can end up with unmaintainable CSS, that will have everyone pulling their hair out.
Performance
People usually negate performance when it comes to CSS, but it is always good to know what is going on when a page is rendered. CSS is read from right to left. Using your example
.wrap header h1 { color: red; }
This means the browser engine will search for every h1 and check if they have a parent header and then if that has a parent class wrap. If so it will apply the style. A low specificity makes the rendering process a lot simpler.
Summary
So to sum it up, nesting, whilst it may seem great keeping your code nice and readable, should only be used when absolutely necessary. It's very easy to forget what the CSS that is actually being produced looks like. Before you know it you'll be in nesting hell.
Languages like LESS or SASS give you more flexibility in declaring your style rules, and that can be good or bad depending on how you use it. The more flexibility you have in a language, the more you need design patterns and good practices to avoid making things worse than they were before.
LESS doesn't require that you always nest. You can always use CSS of course, and if you are applying a style to all p it might be better to define it globally, than to call mixins to obtain the same result on several nested ps.
But LESS and SASS do allow you avoid duplication, to write code that is clearer and easier to maintain, and other problems caused by the code duplication required by CSS.

How to format CSS in a readable way? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I’ve been trying to find out various ways to manage my CSS files which become bigger and bigger as time progresses. This has a few reasons: creating websites using responsive design, plugins that require additional styling or just page-specific styling for a single element.
There are a few techniques I’m already using, like:
Creating a table of contents
Separating code into named sections (to be referred in the table of contents)
Name-spacing the elements (.home-gallery, .home-gallery-image, .home-gallery-link etc.)
Yet there’s still the issue of how to lay down the properties for each element.
Putting everything in a single line significantly decreases the readability. On the other hand, putting each and every property in a single line makes my scrollbar go sit under a shower and cry.
I’m currently experimenting with some different forms, and here’s what I came up with:
Sorting and organizing properties according to their types
Using tabulation/spacing to create a sort of table-look (captions on the left: elements; contents on the right: properties)
In an example it looks as follows:
#content-wrapper {
position: relative; top: 0; left: 0;
width: 100%; height: 200px;
color: #333; background: #fff;
}
For now it seems to me, like the only compromise between having to scroll endlessly/searching for a piece of code and making it less-readable.
So my question is: What CSS writing techniques do you use that allow for good readability and further development?
1) I define style in the order of elements in the HTML
eg: html{ } head{ } body{ } likewise in the order. So while scrolling it will be easy to locate an element for me.
2) Writing styles in the order of screen width, if media query is included. From higher screen width to lower one. Which helps me to find the styles written for media elements easily. There also I follow the first point.
3) Format styles. It is almost like you did.
4) Keeping a documentation.
sample below:
/* indented multi-selectors */
#content-wrapper
, #content-wrapper > something else {
/* alphabetic listing of properties, organizing attributes in blocks */
background-color: #fff;
border-left-width: 2px; /* column layout with blockwise different positioning */
/* separation of blocks */
color: #333;
height: 200px;
left: 0;
position: relative;
top: 0;
width: 100%;
}
probably more important than formatting and organization of individual properties is a clean structure based on conspiring classes and proper documentation, especially of the rules' sequencing (it certainly has been in my projects. often the other way round ... ;-).
imho a decent folding editor sufficiently mitigates the need of frequent scrolling. and large screens, of course.

CSS 'schema' how-to

How does one go about establishing a CSS 'schema', or hierarchy, of general element styles, nested element styles, and classed element styles. For a rank novice like me, the amount of information in stylesheets I view is completely overwhelming. What process does one follow in creating a well factored stylesheet or sheets, compared to inline style attributes?
I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational "tabs" would have class="tabs". A header containing a date could be class="date" or an ordered list containing a top 10 list could have class="chart". Similarly, for IDs, one could give the page footer id="footer" or the logo of the website id="mainLogo". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific.
Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this:
ul.tabs {
list-style-type: none;
}
ul.tabs li {
float: left;
}
ul.tabs li img {
border: none;
}
That way the "parent" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put "body { font-size: 77%; }" and "a { color: #FFCC00; }" etc. After that I would put selectors for the main framework parts of the page, for instance "ul#mainMenu { float: left; }" and "div#footer { height: 4em; }". Then on to common object classes, "td.price { text-align: right; }", finally followed by extra little bits like ".clear { clear: both; }". Now that's just how I like to do it - I'm sure there are better ways but it works for me.
Finally, a couple of tips:
Make best use of cascades and don't "overclass" stuff. If you give a <ul> class="textNav" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {}
Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:
<style>
div.box {
float: left;
border: 1px solid blue;
padding: 1em;
}
div.wide {
width: 15em;
}
div.narrow {
width: 8em;
}
div#oddOneOut {
float: right;
}
</style>
<div class="box wide">a wide box</div>
<div class="box narrow">a narrow box</div>
<div class="box wide" id="oddOneOut">an odd box</div>
Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. "body.signIn div#mainMenu form.signIn { display: none; }"
I hope you find at least some of my ramblings useful and wish you the best with your projects!
There are a number of different things you can do to aid in the organisation of your CSS. For example:
Split your CSS up into multiple files. For example: have one file for layout, one for text, one for reset styles etc.
Comment your CSS code.
Why not add a table of contents?
Try using a CSS framework like 960.gs to get your started.
It's all down to personal taste really. But here are a few links that you might find useful:
http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/
http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/
http://www.louddog.com/bloggity/2008/03/css-best-practices.php
http://natbat.net/2008/Sep/28/css-systems/
Think of the CSS as creating a 'toolkit' that the HTML can refer to. The following rules will help:
Make class names unambiguous. In most cases this means prefixing them in a predicatable way. For example, rather than left, use something like header_links_object2_left.
Use id rather than class only if you know there will only ever be one of an object on a page. Again, make the id unambiguous.
Consider side effects. Rules like margin and padding, float and clear, and so on can all have unexpected consequences on other elements.
If your stylesheet is to be used my several HTML coders, consider writing them a small, clear guide to how to write HTML to match your scheme. Keep it simple, or you'll bore them.
And as always, test it in multiple browsers, on multiple operating systems, on lots of different pages, and under any other unusual conditions you can think of.
Putting all of your CSS declarations in roughly the same order as they will land in the document hierarchy is generally a good thing. This makes it fairly easy for future readers to see what attributes will be inherited, since those classes will be higher up in the file.
Also, this is sort of orthogonal to your question, but if you are looking for a tool to help you read a CSS file and see how everything shakes out, I cannot recommend Firebug enough.
The best organizational advice I've ever received came from a presentation at An Event Apart.
Assuming you're keeping everything in a single stylesheet, there's basically five parts to it:
Reset rules (may be as simple as the
* {margin: 0; padding: 0} rule,
Eric Meyer's reset, or the YUI
reset)
Basic element styling; this
is the stuff like basic typography
for paragraphs, spacing for lists,
etc.
Universal classes; this section
for me generally contains things
like .error, .left (I'm only 80%
semantic), etc.
Universal
layout/IDs; #content, #header,
or whatever you've cut your page up
into.
Page-specific rules; if you
need to modify an existing style
just for one or a few pages, stick a
unique ID high up (body tag is
usually good) and toss your
overrides at the end of the document
I don't recommend using a CSS framework unless you need to mock something up in HTML fast. They're far too bloated, and I've never met one whose semantics made sense to me; it's much better practice to create your own "framework" as you figure out what code is shared by your projects over time.
Reading other people's code is a whole other issue, and with that I wish you the best of luck. There's some truly horrific CSS out there.
Cop-out line of the year: it depends.
How much do you need to be styling? Do you need to change the aspects of alomost every element, or is it only a few?
My favorite place to go for information like this is CSS Zen Garden & A List Apart.
There are two worlds:
The human editor perspective: Where CSS is most easily understand, when it has clear structure, good formatting, verbose names, structured into layout, color and typesetting...
The consumer perspective: The visitor is most happy if your site loades quickly, if it look perfect in his browser, so the css has to be small, in one file (to save further connections) and contain CSS hacks to support all browsers.
I recommend you to start with a CSS framework:
Blueprint if you like smaller things
or YAML for a big and functional one
There is also a list of CSS Frameworks...
And then bring it in shape (for the browser) with a CSS Optimizer (p.e. CSS Form.&Opti.)
You can measure the Results (unpotimized <-> optimized) with YSlow.
A few more tips for keeping organized:
Within each declaration, adopt an order of attributes that you stick to. For example, I usually list margins, padding, height, width, border, fonts, display/float/other, in that order, allowing for easier readability in my next tip
Write your CSS like you would any other code: indent! It's easy to scan a CSS file for high level elements and then drill down rather than simply going by source order of your HTML.
Semantic HTML with good class names can help a lot with remembering what styles apply to which elements.

Resources