Wrapping ID's in CSS Classes? - css

I am relatively new to CSS and wondering whether its possible to "Wrap" ID's so you don't have to repeat them over and over ?
i.e.
#home
{
some stuff
}
#home .header {
some stuff
}
#home .sub_header {
some stuff
}
Is it possible to "wrap" the .header and .sub_header so I don't have to keep repeating #home all the time ? i.e. something like this so the ID can collectively wrap the classes?
#home
{
some stuff
}
##home [
.header {
some stuff
}
.sub_header {
some stuff
}
]

Excellent question! This is not possible with native CSS I'm afraid. There are no real short cuts to take.
If you work with a lot of CSS, there are pre-compilers that allow you to use enhanced notation, and convert it into CSS on the fly.
There's for example
xCSS it can nest child elements.
Then there's LESS, it's written in Ruby so you need that installed (as far as I understand, I haven't used it myself yet) but it's perfectly suitable for editing CSS in any environment. Check the "nested rules" section on the front page.
If you are just getting started with CSS, you may want to stick with the native notation first, though. But the moment it gets really tedious, those tools are a great help.

Unfortunately this isn't possible in just CSS, you can however achieve this using CSS generators such as LessCSS which have their own syntax and have features like nesting and variables.

If you use PHP, consider using lessphp (http://leafo.net/lessphp/docs/), or http://www.symfony-project.org/plugins/sfLessPhpPlugin for symfony

Another great CSS framework is CSS Scaffold
CSS Scaffold is powered by PHP, is easy to use
allows deep selector nesting
constants
custom mixins (reusable pieces of css code)
implements a grid creation framework
caching of already parsed css files for production (+minify)
If you are not coding a big site, I would still recommend plain css

Related

Using nth-child or creating new classes in CSS?

I've just started my first project which is building an admin panel. My task is to create HTML and CSS - sort of a base of design to process further to the back-end developers.
I was asked to keep CSS simple and classes as descriptive as possible ( could be long ) and to use Bootstrap.
To avoid creating unnecessary classes which could be used once or twice I decided to go with :nth-child since I thought giving new class to each column is too much. Additionally I created few base classes that might be used for adding 0px padding and margin.
Unfortunately, as I was writing more and more code I've noticed that some CSS code looks like this:
.print-history-advanced-search > [class*='col-']:nth-child(5) > .form-group > .form-horizontal > .form-group > [class*='col-']:first-child
And it is not a single line.
Additionally, I've noticed that sometimes that when I am making a new class and it has lots of parent elements, I cannot write the CSS selector by its own, but I need to state the parents of the this particular element and put the class at the end, which does not make sense.
Is there any solution I could use to avoid creating classes that are simply used in one or two divs, but also make the CSS code less chaotic and avoid very long names? Or maybe I should just give up on children and nesting and work with just classes?
Thank you for your help!
Have a nice day!
If you want to write good CSS, then I'd suggest the BEM model is a good route to go down.
The essentials are;
No element/selector heirachy
No use of elements in selectors
Class based styles only
BEM stands for Block, Element, Modifier - which is how your class names are formed. Borrowing an example from their site;
.form { }
.form--theme-xmas { }
.form--simple { }
.form__input { }
.form__submit { }
.form__submit--disabled { }
<form class="form form--theme-xmas form--simple">
<input class="form__input" type="text" />
<input
class="form__submit form__submit--disabled"
type="submit" />
</form>
You can see there's a form Block, and then a form__input and form__submit Element, and then a form__submit--disabled Modifier.
Depending on your needs I would recommend using css preprocessors like SASS,LESS.
You’ll find that as a website grows, you’ll develop a pretty long, scrolling list of various elements and CSS rules. Some of the rules might overlap or override each other eventually (in that case, usually the more specific rule will win).
You can end up with a lot more code than you expected, especially considering the different variations of a rule you need for different browsers and screen sizes.
There are many ways to refactor your CSS code to make it easier to navigate and use. Some of the easiest methods are the most effective and have the most mileage. Here are some of the quickest ones:
Keep your spacing uniform: Maintain the same spacing between rules
and within declarations throughout your file so that it’s easier to
read.
Use semantic or “familiar” class/id names: Instead of using a class
name like “bottom_menu”, try using the semantic tag “footer”. Or
when you have an image in your “contact” section, make sure you’re
using a class on your image like “contact_image”
Keep it DRY (Don’t Repeat Yourself): Ideally you want to repeat as
little of your code as possible. Do you find the declaration
“background-color: #000″ repeated throughout your CSS file? Consider
typing it once and instead, using multiple selectors on the one
declaration.
Put your tidiness to the test with these tools: Run your CSS through
CSS Lint or W3C—these will help to parse your CSS file correctly,
and highlight problem areas. Your web browser’s developer tools are
also extremely useful for pinpointing specific elements on your
website and using the area as a sandbox to experiment with different
styles and positioning.
Have a look here for more info

Confusion with BEM modifiers

I have started using BEM methodology while writing my CSS and there have been few occasions where I have struggled to find out the best way to do a particular thing.
I would like to take up a simple example of a panel here.
Lets say I am writing a panel component CSS using BEM style. So my CSS might look as follows:
.panel {}
.panel__titlebar {}
.panel__content { display: none; }
A panel can be either chromeless or with chrome. So I define another modifier class for the panel:
.panel--with-chrome {
border: 4px solid black;
border-radius: 4px;
}
Now lets say, the panel can be in a fullscreen/maximized state also in which the chrome and titlebar disappear. Instead of defining modifiers for both panel and titlebar, it would be be wise to define the modifier just on parent (say panel--fullscreen) and rest elements shall change accordingly. So now my CSS becomes:
.panel--fullscreen {
/* something has to be done here */
}
.panel--fullscreen .panel__titlebar { display: none; }
To remove the chrome in fullscreen mode, I can either:
toggle the panel--with-chrome class in JS along with the panel--fullscreen class
overwrite the chrome CSS inside the panel--fullscreen class.
First isn't good because ideally I would like to simply toggle just one class (.panel--fullscreen) in JS to toggle fullscreen mode.
And second one is bad because I'll have to overwrite previous CSS which is a bad practice.
So whats the best way to go about it? Appreciate your comments.
Thanks
The answer depends on many things.
First, how much logic and appearance have "panel--with-chrome" and "panel--fullscreen" modifiers. And also on what kind this logic is.
If "panel--with-chrome" brings a lot of CSS properties and special JS functionality, I would toggle it in JavaScript when applying "panel--fullscreen".
It also depends on a JavaScript framework you use. In "i-bem.js" which we use at Yandex it's easy to react to appending a modifier:
A square changes size modifier when after a click
Reacting on applying a modifier
But if the framework you use doesn't allow to express such a reaction handy, this answer won't work that great for you.
In the other case, when "panel--with-chrome" has not very much properties and doesn't bring any JavaScript logic to a page, I would redefine those CSS properties in "panel--fullscreen" class.
To sum up, there is no universal solution and strict rules to follow. You should decide yourself what will be useful in your case. The decision should depend on many things:
if you expect your project to be maintained in the future, which solution will be easier to support?
capabilities of the JavaScript framework you use
performance stuff
Not in this particular case, but sometimes we measure speed of rendering for variants we are choosing from.
opinion of the other guys, if you work in team
file structure of your project
We, here at Yandex, store CSS and JavaScript for a block in the same block folder. So, it is not a problem to share logic between CSS and JavaScript since they all are in one place.
But if you keep your JavaScript files separately, this can influence on how comfortable it is to support shared logic.
And so on...
I’d go with the first option; you are toggling state after all, so you need to add/remove/toggle classes accordingly. It’s better than undoing a load of stuff in CSS IMO.

Nested CSS Selectors in CSS

Is there a way to create a css group inside of a css selector.
Eg:
.SectionHeader
{
include: .foo;
include: .bar;
include: .baz .theta .gamma .alpha .omega .pi .phi;
}
Trying to see if there is a way to do this at the CSS level instead of inside of a class=".foo .bar .baz .theta .gamma .alpha .omega .pi .phi" tag. I have to use the combination of classes in a few places and want to avoid all that cut and paste.
No, you can't do this in pure CSS as things stand.
There are some moves afoot to extend CSS to allow things like this, but it's very early days Google has some demonstrated some extended syntax working in a dev version of Chrome, but it'll be a while before it goes live, and even longer before it has sufficient cross-browser support to be actually useful.
In the meanwhile though, there are a number of CSS extension products available which allow you to write stylesheets with nested rules, etc. You would then need to run your stylesheets through a parser to convert them into "real" CSS before you put them on your site, but it might be a compromise you're prepared to make.
If so, check out SASS and Less, among others.
[EDIT]
By the way, I mentioned that Google have been demonstrating some extended CSS syntax. Here's a link to a blog post about it: http://www.xanthir.com/blog/b49w0
No, but as you stated you can assign multiple classes to an element:
<div class="SectionHeader foo bar"></div>

Css Best Practice Dilemma - specific case

A client asks for an admin table and one column will have different cell colors based on some rules.
My problem is : what is the best css practice for this.
we know inline is bad from the start
we could do some css classes for each color and give them a good name but this will just clutter then main css file with classes that will probably never be used again.
So what would be a good approach for this simple problem ?
So what would be a good approach for this simple problem ?
You have essentially already outlined your two options. It's your choice.
I would always go with classes, and never with inline CSS. If you're worried about cluttering, you could add some order using comments:
/** Table highlight styles **/
table.data td.highlight { background-color: #CCCCCC }
table.data td.total { background-color: #ABCDEF }
You could theoretically put these into a separate CSS file, but the number of style sheets should be kept as low as possible. To do this right, you could use a CSS preprocessor as suggested by #Ian.... but that is an entirely different and new can of worms.
Personally, I would recommend using something like dotless(DotNet) or less (Ruby).
Here you can define a colour like #MyMainColour and then have div.SomeBackground { background: #MyMainColour; }
These tools will allow you to "compile" your CSS compress and turn out customer specific themes.
You might consider:
Keep a separate css file for specific adjustments. This might be a good compromise between keeping a main style file uncluttered, but still be able to target specific GUIs with adjustments.
Let a GUI have an id. This way you can let GUI specific adjustments only affect that GUI with styles given in context.

How to remove CSS spaghetti in legacy web app?

After working on several large web applications, and seeing gigantic style sheets with no clear structure, I'd really love to know if people have found ways to keep their css clean for large and complicated web apps.
How do you move from a legacy, mess of css to cleaned up, nicely cascading, DRY stylesheets?
The app I'm currently working on has 12000 lines of css. It's grown to this size organically as early on there were no standards or review of the css, the only rule was to make the app match the design. Some of the problems we constantly have:
Conflicting styles: one developer adds a .header { font-weight: bold;} but .header was already used in other modules and shouldn't be bold in those.
Cascading problems: Foo widget has a .header but it also contains a list of Bar widgets with .header classes.
If we define .foo .header { ... } and .bar .header { ... } anything not explicitly overwritten in foo will show up in bar.
If we define .foo > .header and .bar > .header but later need to modify foo to wrap header in a div, our styles break.
Inheritance problems, we constantly redefine widget fonts to 11px/normal because some top container uses a 12px / 18 px line height.
Fighting against widget libraries, using libraries such as dojo/dijit or jquery ui that add tons of styles to be functional means that our code is littered with places where we have to override the library styles to get things looking just right. There are ~2000 lines of css just for tweaking the builtin dijit styles
We're at a point where we're thinking of implementing the following rules:
Namespace all new widget classes - if you have a widget foo all sub-classnames will be .foo_ so we get: .foo, .foo_header, .foo_content, .foo_footer. This makes our css essentially FLAT, but we see no other way to organize our code going forward without running into the legacy styles or the cascading problems I mentioned above.
Police generic styles - have a small handful of generic classes that are only to be applied in very specific situations. e.g. .editable - apply to portions of a sentence that should invoke an editor - should only contain text nodes.
Leverage css compiler mixins To avoid repeatedly defining the same styles in different widgets, define and use mixins. Although we worry the mixins will get out of control too.
How else can we move from css mess that constantly introduces regressions to something maintainable going forward.
We're using a style guide in the form of a simple HTML page with examples of every CSS rule in the stylesheet. It's very easy to tell if you add a new, incompatible rule since the examples are aligned on top of eachother.
An example I like: http://getbootstrap.com/components/ (added 2015)
The other pro you get from this method is reusability: you know what you got and you know that you want the style guide to be as small as possible - therefore: reuse.
When you make changes to styles already in use: check the style guide. If it doesn't change it's probably good (you might need to browse around a bit if you've just changed something including box model-issues, or width, height, padding, margin in general).
How do you move from a legacy, mess of
css to cleaned up, nicely cascading,
DRY stylesheets?
Use the style guide as a unit test. Once you got the essential parts in it: reduce, refactor and combine (you most probably will find some collissions between .campaign_1 span and your regular rules, inheritance can be your friend).
Conflicting styles: one developer adds
a .header { font-weight: bold;} but
.header was already used in other
modules and shouldn't be bold in
those.
In reply to Adriano Varoli Piazza's comment and the quote above: I don't recall this as a problem fully belonging to the CSS but more to the HTML markup. No matter what you do, it will be some heavy lifting. Decide which rule you'd want to keep and take actions towards cleaning out the lesser-used-ones; for example: via inheritance: #news a .header { ... } or renaming the HTML-class a .stand_out_header { ... }.
About the following idea
Namespace all new widget classes - if
you have a widget foo all
sub-classnames will be .foo_ so we
get: .foo, .foo_header, .foo_content,
.foo_footer. This makes our css
essentially FLAT, but we see no other
way to organize our code going forward
without running into the legacy styles
or the cascading problems I mentioned
above.
Use a containing element instead, which will be much more easy to maintain:
<div id="widget_email">
<h2>One type of h2</h2>
</div>
<div id="widget_twitter">
<h2>Another h2</h2>
</div>
I find that the method for "namespacing" and limiting conflict in CSS is separate into different includes what you want to apply, so each page calls only what it needs. Conflicting rules can then be made more specific simply by defining them in a more particular include:
general css for all pages
css for pages in section A
css for pages in section B
So if you find a .header modification you added in the general css works in A but doesn't in B, you simply move it to the lower CSS file.
Yes, this implies more files to load. There are ways around it with server-side languages, like reading all files with php and sending only one block of content.

Resources