Using nth-child or creating new classes in CSS? - 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

Related

Using existing CSS selectors to apply styles across the Shadow DOM to custom elements

This question likely has no single direct answer, but hopefully will lead to some best practices or common patterns to use when adapting an existing styles framework to new web component development.
For my case, I have a component <custom-avatar>, and it's all set up properly with self-contained styles and functionality, everything is just peachy.
In certain use cases, the application display needs to stack avatars, just one slightly overtop one other at a diagonal, and the pattern I'm following is using a simple component <custom-composite-avatar>. All this does is wrap the slotted content in a <div> with the correct styling class, but key aspect is retaining the composability for flexible re-use, like so:
<custom-composite-avatar>
<custom-avatar title="first"></custom-avatar>
<custom-avatar title="second"></custom-avatar>
</custom-composite-avatar>
The tricky bit lies in the styles, which are imported from a monorepo that provides the same BEM-ish CSS and component CSS modules to other flavors of the component library like React, Vue, etc. I have the avatar and composite-avatar styles imported just fine, but forcing the intended overlap display is defined with the hierarchical selector .my-composite-avatar.my-composite-avatar--medium .my-avatar {}
So with .my-composite-avatar class applied to the div wrapper within <custom-composite-avatar> and the .my-avatar class applied to the wrapper within the <custom-avatar> and it's own Shadow DOM, that parent/child CSS selector is no good.
I doubt there is a silver bullet for this, but this seems like it will be a rather common scenario as more people migrate to Web Components while using existing styling systems. What approach makes the most sense to ensure that the composite component remains composable, and adaptation of existing selectors pain-free (or at least easy to communicate to other devs)? can this be solved with ::host or ::slotted, or will these cases require significant re-work?
Thanks for reading, your ideas are appreciated!
I would advice to become good friends with CSS properties
because they trickle down into shadowDOMs following CSS selectors.
CSS Custom Properties(variables)
and getPropertyValue
and setProperty if you want to be brutal and make Custom Elements change the outside world.
example
I have an <SVG-ICON> element taking configuration from attributes OR CSS properties
with my favorite lines of code:
let val = this.getAttribute(attr)
||
getComputedStyle(this)
.getPropertyValue("--svg-icon-" + attr)
.replace(/"/g, "")
.trim();
Allows for your standard attribute configuration:
<svg-icon name="configuration" fill="grey"></svg-icon>
But more powerful (simplified example):
<style>
body {
--svg-icon-fill: "grey";
}
svg-icon[selected] {
--svg-icon-fill: "green";
}
</style>
<svg-icon name="messages" selected></svg-icon>
<svg-icon name="configuration"></svg-icon>
CSS = Custom String Scripting
It doesn't often happen, but sometimes the simplest code makes me very happy.
There is no Styling restriction!
These 2 lines allow any String you want in CSS properties:
.replace(/"/g, "")
.trim();
Example
<style>
[name*="globe"] {
--svg-icon-tile: "rect:0,0,24,24,0,fill='blue'";
--svg-icon-stroke: white;
}
</style>
<svg-icon name="feather-icons-globe"></svg-icon>
The --svg-icon-tile has nothing to do with CSS, it is read (and parsed) by the <SVG-ICON> connectedCallback() code to generate a SVG background/tile for all icons named globe.
The double-quotes aren't required, but without them your IDE will complain about invalid CSS.
Have fun coding... you will pull some hairs when you start with calc() in your CSS properties...
But you can take 'CSS' to another level.
PS.
And monitor the future of ConstructAble StyleSheets aka ConstructIble StyleSheets aka Constructed Sheets aka AdoptedStyleSheets:
https://developers.google.com/web/updates/2019/02/constructable-stylesheets
https://chromestatus.com/feature/5394843094220800
iconmeister

BEM Common Styles

What is the best way of defining general non-block-specific styles throughout the site?
For example:
html
<div class="intro">
<p class="intro__text">foo</p>
</div>
<div class="profile">
<p class="profile__text">bar</p>
</div>
sass/css
.intro__text {
}
.profile__text {
}
.text {
margin-bottom: 0.5em;
}
If I wanted the text to be styled the same, would I (given I am using a pre-processor) #extend .text into the .intro__text and .profile__text classes, or just have all paragraphs throughout the site have a class of text?
Both those solutions seem slightly incorrect to me.
If I have a very common style, it feels like I'm going to be duplicating a lot of styles throughout my rendered css (bumping up the filesize) but having a class of text repeated all throughout my markup seems unnecessarily verbose and untidy.
Is there a best practice for this situation?
I can't say that there is the best way to do it. It depends on the structure of your project and what style your prefer. Both approaches are used in mostly code.
If you like to manage styles through css files - write #extend. However in case you want an element without common style you have to create a modifier for the el. For example - .profile__text--reset.
If you want declare common styles, your class list with common classes may become too long. But it is more clear and specific. And you have a possibility to manage it via javascript.
One improvement for this code is that it is better to use helpers with modifiers. For example, instead of simple .text use .text--sm or .text--m-sm. Or if you want only margin - .m-sm. But it is up to you.
You have several options:
Preprocessor (Sass/LESS/etc) mixins + clean-css/postcss cleaner — this way is simple and powerful, but not flexible, since it's not useful for dynamic landing pages, SPA, etc.;
Element of outer block mix (BEM/runtime mixin): class="intro__text grid__text" — in that way you just splitting manually visual and positioning styles and use their classes together;
Other block mix: class="intro__text paragraph paragraph--valuable" — almost like the previous variant but without linking to the abstract grid block, the best and the most flexible way (IMHO).
NB: Also you can extend BEM mixes with modifiers even in runtime, it's VERY powerful tool.
NB2: If you don't need dynamic web pages, you can freely use sass mixins. Personally I don't use sass/less mixins, only global variables for colors, grid, gaps, etc used in my own classes.

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.

What's so bad about in-line CSS?

When I see website starter code and examples, the CSS is always in a separate file, named something like "main.css", "default.css", or "Site.css". However, when I'm coding up a page, I'm often tempted to throw the CSS in-line with a DOM element, such as by setting "float: right" on an image. I get the feeling that this is "bad coding", since it's so rarely done in examples.
I understand that if the style will be applied to multiple objects, it's wise to follow "Don't Repeat Yourself" (DRY) and assign it to a CSS class to be referenced by each element. However, if I won't be repeating the CSS on another element, why not in-line the CSS as I write the HTML?
The question: Is using in-line CSS considered bad, even if it will only be used on that element? If so, why?
Example (is this bad?):
<img src="myimage.gif" style="float:right" />
Having to change 100 lines of code when you want to make the site look different. That may not apply in your example, but if you're using inline css for things like
<div style ="font-size:larger; text-align:center; font-weight:bold">
on each page to denote a page header, it would be a lot easier to maintain as
<div class="pageheader">
if the pageheader is defined in a single stylesheet so that if you want to change how a page header looks across the entire site, you change the css in one place.
However, I'll be a heretic and say that in your example, I see no problem. You're targeting the behavior of a single image, which probably has to look right on a single page, so putting the actual css in a stylesheet would probably be overkill.
The advantage for having a different css file are
Easy to maintain your html page
Change to the Look and feel will be easy and you can have support for many themes on your pages.
Your css file will be cached on the browser side. So you will contribute a little on internet traffic by not loading some kbs of data every time a the page is refreshed or user navigates your site.
The html5 approach to fast css prototyping
or: <style> tags are no longer just for the head any more!
Hacking CSS
Let's say you're debugging, and want to modify your page-css, make a certain section only look better. Instead of creating your styles inline the quick and dirty and un-maintainable way, you can do what I do these days and take a staged approach.
No inline style attribute
Never create your css inline, by which I mean: <element style='color:red'> or even <img style='float:right'> It's very convenient, but doesn't reflect actual selector specificity in a real css file later, and if you keep it, you'll regret the maintenance load later.
Prototype with <style> instead
Where you would have used inline css, instead use in-page <style> elements. Try that out! It works fine in all browsers, so is great for testing, yet allows you to gracefully move such css out to your global css files whenever you want/need to! ( *just be aware that the selectors will only have page-level specificity, instead of site-level specificity, so be wary of being too general) Just as clean as in your css files:
<style>
.avatar-image{
float:right
}
.faq .warning{
color:crimson;
}
p{
border-left:thin medium blue;
// this general of a selector would be very bad, though.
// so be aware of what'll happen to general selectors if they go
// global
}
</style>
Refactoring other people's inline css
Sometimes you're not even the problem, and you're dealing with someone else's inline css, and you have to refactor it. This is another great use for the <style> in page, so that you can directly strip the inline css and immediate place it right on the page in classes or ids or selectors while you're refactoring. If you are careful enough with your selectors as you go, you can then move the final result to the global css file at the end with just a copy & paste.
It's a little hard to transfer every bit of css immediately to the global css file, but with in-page <style> elements, we now have alternatives.
In addition to other answers.... Internationalization.
Depending of the language of the content - you often need to adapt the styling of an element.
One obvious example would be right-to-left languages.
Let's say you used your code:
<img src="myimage.gif" style="float:right" />
Now say you want your website to support rtl languages - you would need:
<img src="myimage.gif" style="float:left" />
So now, if you want to support both languages, there's no way to assign a value to float using inline styling.
With CSS this is easily taken care of with the lang attribute
So you could do something like this:
img {
float:right;
}
html[lang="he"] img { /* Hebrew. or.. lang="ar" for Arabic etc */
float:left;
}
Demo
Inline CSS will always, always win in precedence over any linked-stylesheet CSS. This can cause enormous headache for you if and when you go and write a proper cascading stylesheet, and your properties aren't applying correctly.
It also hurts your application semantically: CSS is about separating presentation from markup. When you tangle the two together, things get much more difficult to understand and maintain. It's a similar principle as separating database code from your controller code on the server side of things.
Finally, imagine that you have 20 of those image tags. What happens when you decide that they should be floated left?
This only applies to handwritten code. If you generate code, I think that it's okay to use inline styles here and then, especially in cases where elements and controls need special treatment.
DRY is a good concept for handwritten code, but in machine-generated code, I opt for "Law of Demeter": "What belongs together, must stay together". It's easier to manipulate code that generates Style tags than to edit a global style a second time in a different and "remote" CSS file.
The answer to your question: it depends...
Using inline CSS is much harder to maintain.
For every property you want to change, using inline CSS requires you to look for the corresponding HTML code, instead of just looking inside clearly-defined and hopefully well-structured CSS files.
The whole point of CSS is to separate content from its presentation. So in your example you are mixing content with presentation and this may be "considered harmful".
In addition to the other answers, another concern is that it violates the recommended Content Security Policy from MDN, https://infosec.mozilla.org/guidelines/web_security#content-security-policy
The justification they use is that inline javascript is harmful, XSS, etc., but it doesn't justify why inline styles should also be disabled. Maybe someone can comment as to why, but until then, I'll just rely on appeal-to-authority and claim: it's a security best practice to avoid inline styles.
Code how you like to code, but if you are passing it on to someone else it is best to use what everyone else does. There are reasons for CSS, then there are reasons for inline. I use both, because it is just easier for me. Using CSS is wonderful when you have a lot of the same repetition. However, when you have a bunch of different elements with different properties then that becomes a problem. One instance for me is when I am positioning elements on a page. Each element as a different top and left property. If I put that all in a CSS that would really annoy the mess out of me going between the html and css page. So CSS is great when you want everything to have the same font, color, hover effect, etc. But when everything has a different position adding a CSS instance for each element can really be a pain. That is just my opinion though. CSS really has great relevance in larger applications when your having to dig through code. Use Mozilla web developer plugin and it will help you find the elements IDs and Classes.
I think that even if you want to have a certain style for one element, you have to consider the possibility that you may want to apply the same style on the same element on different pages.
One day somebody may ask to change or add more stylistic changes to the same element on every page. If you had the styles defined in an external CSS file, you would only have to make changes there, and it would be reflected in the same element in all of the pages, thus saving you a headache. :-)
Even if you only use the style once as in this example you've still mixed CONTENT and DESIGN. Lookup "Separation of concerns".
Using inline styles violates the Separation of Concerns principle, as you are effectively mixing markup and style in the same source file. It also, in most cases, violates the DRY (Don't Repeat Yourself) principle since they are only applicable to a single element, whereas a class can be applied to several of them (and even be extended through the magic of CSS rules!).
Furthermore, judicious use of classes is beneficial if your site contains scripting. For example, several popular JavaScript libs such as JQuery depend heavily on classes as selectors.
Finally, using classes adds additional clarity to your DOM, since you effectively have descriptors telling you what kind of element a given node in it is. For example:
<div class="header-row">It's a row!</div>
Is a lot more expressive than:
<div style="height: 80px; width: 100%;">It's...something?</div>
Inline CSS is good for machine-generated code, and can be fine when most visitors only browse one page on a site, but one thing it can't do is handle media queries to allow different looks for screens of different sizes. For that, you need to include the CSS either in an external style sheet or in an internal style tag.
In-page css is the in-thing at the moment because Google rates it as giving a better user experience than css loaded from a separate file. A possible solution is to put the css in a text file, load it on the fly with php, and output it into the document head. In the <head> section include this:
<head> ...
<?php
$codestring = file_get_contents("styles/style1.txt");
echo "<style>" . $codestring . "</style>";
?>
... </head>
Put the required css in styles/style1.txt and it'll get spat out in the <head> section of your document. This way, you'll have in-page css with the benefit of using a style template, style1.txt, which can be shared by any and all pages, allowing site-wide style changes to be made via only that one file. Furthermore, this method doesn't require the browser to request separate css files from the server (thus minimising retrieval / rendering time), since everything is delivered at once by php.
Having implemented this, individual one-time-only styles can be manually coded where needed.
According to the AMP HTML Specification it is necessary to put CSS in your HTML file (vs an external stylesheet) for performance purposes. This does not mean inline CSS but they do specify no external stylesheets.
An incomplete list of optimizations such a serving system might do is:
Replace image references with images sized to the viewer’s viewport.
Inline images that are visible above the fold.
Inline CSS variables.
Preload extended components.
Minify HTML and CSS.
Personally, I think the hatred of inline css is just ridiculous. Hardcore cult behaviour, people just sheepishly repeat "Separation of concerns!". Yes, there are times where if there is a repeating element and you will need repeated styling to use a class targeted from a CSS file, but most of the time it improves speed of development and CLARITY OF CODE to put the style inline, it's great if I can look at the code and see that there is a custom margin height, it helps me picture the HTML document as a whole, instead of some named class that gives me little insight into which styles will be applied.
So I will be the contrarian here and say that inline css is great and that people who scream at you for using it are just following what they have been told without actually giving it any original unbiased consideration.
Even though I totally agree with all the answers given above that writing CSS in a separate file is always better from code reusability, maintainability, better separation of concerns there are many scenarios where people prefer inline CSS in their production code -
The external CSS file causes one extra HTTP call to browser and thus additional latency. Instead if the CSS is inserted inline then browser can start parsing it right away. Especially over SSL HTTP calls are more costly and adds up additional latency to the page. There are many tools available that helps to generate static HTML pages (or page snippet) by inserting external CSS files as inline code. These tools are used at the Build and Release phase where the production binary is generated. This way we get all the advantages of external CSS and also the page becomes faster.
In addition to other answers, you cant target the pseudo-classes or pseudo-elements in inline CSS
We have created a template-driven artifact generator that provides an include file capability for any kind of text artifact -- HTML, XML, computer languages, unstructured text, DSV, etc. (E.g., it's great for handling common Web or manual page headers and footers without scripting.)
Once you have that and use it to provide "style" tags inside your "head" tag, the "separation of concerns" argument goes away, to be replaced by "we have to regenerate after every change to the template" and "we have to debug the template from what it generates". Those gripes have been around since the first computer language to get a preprocessor (or someone started using M4).
On balance, we think the meta-izing capability of either a CSS file or "style" tags is cleaner and less error-prone than element-level styling. But it does require some professional judgment, so newbies and scatterbrains don't bother.

is using class names like 'right' considered bad practice?

If I have class names such as "left", "right", "clear" and xhtml like
Continue
With CSS like
.right {
float: right;
}
I know it's not a semantic name, but it does make things much easier sometimes.
Anyway, what are your thoughts?
I don't think that's a very good idea. Now when you (or a future maintainer) go to change your website layout, you'll either have to change .right to {float:left;} (obviously a bad idea) or go through all your HTML files and change right to left.
Why do you want that particular link to be floated right, and the other .continueLink's not to? Use the answer to that question to choose a more descriptive class name for that link.
css is about presentation of the structure of your html page.
Meaning its classes should represent the structure of the document ('article', 'extra-links', 'glossary', 'introduction', 'conclusion', ...).
You should avoid any class linked to a physical representation ('left', 'right', 'footnotes', 'sidenotes', ...), because, as the Zen Garden so clearly illustrates, you can decide to place any div in very different and various ways.
The purists will say don't do it, and the pragmatists will say it's fine. But would the purists define .right as float: left?
It might be advisable to avoid names that are the same as values in the CSS specs to avoid confusion. Especially in situations where multiple developers work on the same application.
Other than that I see no problem. I would qualify the right or left name like this: menuleft, menuright etc.
Being a purist, I say no don't do it. For reasons mentioned earlier.
Being a pragmatist, I just wanted to say that never have I seen website rework that involved pure html changes without css, or pure css without html, simply because both parts are being developed with the other in mind. So, in reality, if somebody else would EVER need to change the page, I bet my salary they will change both html and css.
The above is something that collegue purists around often tend to ignore, even though it's reality. But bottom line; no, avoid using a className such as "right". :-)
.right and other classes like that, certainly makes it quick to write create a tag with a float:right rule attached to it, but I think this method has more disadvantages than advantages:
Often a class-style with a single float:right; in it will lack something, your example wil only float right if the other class rule contains a display:block in it, since an "a" tag is not a block level element. Also floating elements more often than not needs to have width an height attached. This means that the code in your example needs additional code to do what it says, and you have to search in two places when you have to change your css.
I tend to style my html by dividing the page into different div-tags with unique id's, and then styling elements in these div by inheritance like this.
div#sidebar { float:right; width:200px; }
div#sidebar ul { list-style-type:none; }
This makes it possible to partition my css files, so that it is easy to find the css-code that styles a particular tag, but if you introduce .right and other classes you are starting to disperse the rules into different areas of the css file, making the site more difficult to maintain.
I think the idea of having a very generic classes is born from the wish of making it possible to change the entire layout of the site by changing a couple of rules in a stylesheet, but I must say that in my 8 years of website development with 30+, different sites under my belt i haven't once changed the layout of a website and reused the HTML.
What I have done countless times is making small adjustments to regions of pages, either due to small changes in the design or to the introduction of new browsers. So I'm all for keeping my css divided into neat chunks that makes it easy to find the rules I am looking for, and not putting the code in different places to achieve a shorter stylesheet.
Regards
Jesper Hauge
Yeah, semantically speaking it is wrong, but, for example, there are times when I'm positioning images within a block of body copy and I'll give them the class "right".
Maybe "alt" is a more suitable class name.

Resources