Use of CSS Helper Class - css

I try to code CSS in "Help Class Style" today and many developers on Twitter said it was a bad practice.
Here is an example:
<span class="et-margin-top-30 et-width-400 et-display-inline">
<p class="et-common-frame-shadow et-inner-img-shadow">
<img class="et-common-frame-img" src="img3.jpg"/>
</p>
<h3 class="et-margin-top-10 et-fontsize-26 et-fontweight-bold">foo</h3>
<p class="et-margin-top-10">bar</p>
</span>
Why is it a bad practice? When should we use a helper class such as .clear?

The idea of styling via CSS is separation between content and styling. Your content is in HTML and CSS provides the information on how that should be visually displayed. If you want to change one, you can do so without changing the other.
By naming your classes et-margin-top-30, you're putting the styling information back into your HTML. You may as well write style="margin-top: 30px". Because if you decide that that element should have a 50 pixel margin after all, you need to change both the CSS and the HTML. That's why it's bad style.
You should rather name your HTML elements by their function (e.g. class="headline", or class="call-to-action"), then describe in your CSS how that headline or that call-to-action should be styled. If you want to change that later, you can do so by simply editing your CSS, the HTML doesn't need to change.
Not to mention that if you're using Javascript to manipulate elements, using document.getElementsByClassName('et-margin-top-30') a) makes it very hard to understand the meaning of your scripts and HTML structure and b) requires that you modify your HTML, CSS and Javascript every time you want to tweak the visual appearance of an element. Using descriptive class names becomes doubly important then.

What you are trying to do there looks horrible. It looks like you have a class for all different styling attributes. Not only will it make your HTML unreadable, but it will also enlarge the file size.
What if an element has 15 styles "attached" to it. Will it have 15 classes?
I also think this will only make this slower to render (this is just something I just made up and for which I have no proof), because it has to look up all those classes.
I don't see any difference in doing <p style="color: red;"></p>.

Related

What to do when the Block element in a BEM component doesn't need any styles?

Let's say I have a structure like this:
<article class="product">
<header class="product__header">
<h1 class="product__headline">Headline</h1>
<img class="product__hero" src="" alt="">
</header>
<p class="product__description">Content</p>
</article>
As the Block element article brings all the styles it needs by default, it actually doesn't have any CSS. So I'm not defining it in the CSS like this, because it only clutters the styles:
.product { }
But I'm unsure about the HTML. Should it be
<article class="product"></article>
… anyways or simply …
<article></article>
… as there are no styles attached?
What is the right thing to do when usin BEM?
As I understand it, the idea with BEM is to use a standard and have a markup ready for any present or future CSS, so you would always include the class, even if you don't use it right now.
Another good reason is that the parent class improves readability and order for anyone looking at the markup. I would even suggest you to include the class in your CSS and left it blank, functioning almost like a subtitle, with the potential to be useful later on.
Finally, BEM recommends against nesting elements in the stylesheet, which means preferring the use of classes even in the smallest children (like a strong tag inside a p). Seems natural, then, to have a class in the parent as well.
Keep the class to keep your independence. Future changes might require you style . This approach has several advantages:
In 2 months you'll still be able to determine the module components and structure without further ado
You and everybody else will know that is the component container even if you add further wrapping elements in-between.
You might be able to alter the layout without touching the HTML
No dependency between HTML semantics and layout.
All present structure is mirrored into the layout so you can see all variants and elements in the CSS. Get things out of your head
Finally, I agree with you that CSS clutter isn't nice but it could be useful, especially when you're working on a larger codebase with a larger team where you need to rely on standards.
On your parser/IDE: it will probably be configurable to ignore such entries. Your build process should be able to remove these empty selectors so it doesn't make its way into production CSS.
I have come across a similar scenario, If you are following BEM, then keep that class in the article element, since it will help in maintenance(such as removing unused styles, better understand markup).
for example(in product.scss):-
.product {
&__header {
font-size: 1.7rem
// etc...
}
}
Hope this helps. Happy coding....
Note:- Depends upon your markup, you can hoist block element class responsibility to the parent element and updated child class with new parent class.(eg:- .root__prdHeader)

BEM and single selectors

This is sort of a theoretical question, but it bugs me for a couple of hours now.
I'm learning BEM and it's great so far, but I have a problem. Let's say I have this code:
<div class="section-hi main-section">
<h2 class="main-section_header">Blah</h2>
<p>Generated from the CMS</p>
</div>
How do I target the p to make it good with BEM? Can I just go with
.main-section p
or this would be against the rules? I coudn't find any answers to this, since every example and article about BEM focuses only on classes, and I can't expect my CMS to add different class to every groups of paragraphs.
One of the concepts of BEM is to create reusable components, using an element such as p goes against that.
Why?
By specifying p we are restricting the ways in which our component can be used. To display correctly the p tag must be used. For example the following markup would not work with the component.
<div class="section-hi main-section">
<h2 class="main-section_header">Blah</h2>
<span>Generated from the CMS</span> <!-- this will not pick up the styles -->
</div>
Specificity
Another important point is BEM aims to keep specificity to a minimum, using single class names. Creating a style with a p increases specificity.
.main-section p
It is now hard for me to override this style with a utility class, as it has a higher specificity than a single class.
More on CSS specificity
The solution
So instead the idea is to use class names to describe the element. That way we can choose to use whatever markup we like and the component will display as expected. e.g.
<div class="section-hi main-section">
<h2 class="main-section_header">Blah</h2>
<h3 class="main-section_subHeader>Generated from the CMS</h3> <!-- This will work -->
</div>
Must I always use class names?
You will find occasions when it is OK or necessary to create styles for elements and not use class names. For example you may have a component that you only want to be used with certain markup. Then it is perfectly valid to do so.
Summary
As a general rule always try and keep to the single class rule unless there is a valid reason not to do so. Otherwise it will trip you up later on down the line.
For further reading on BEM I recommend this post http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/
If we just look on this code - you can do that, but what if you have more <p> elements? If you can't add class to every element, you can always add id and call element by
#element_id{ }

Setting a class in the stylesheet instead of the markup

I'm trying to apply my poor knowledge of CSS to a little toy project I have going, and it's annoying me endlessly that I have to declare column widths in my HTML markup.
Is there a way so that I can, instead of
<div class="grid_4"></div>
use something like
<div id="leftNav"></div>
and in the stylesheet apply the grid_4 class to the element with id leftNav?
In my mind it would look something like this
#leftNav {
apply-class: grid_4;
}
Is there anything like that available in CSS?
Not in regular CSS, no.
There are CSS preprocessors though, which create a new mini-language which then gets processed into regular CSS, which add those and more features. See less, Sass.

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.

View css styles in a demo page

Is there an app out there that will take a .css file and output a demo page of it?
Like take all the span/div/a elements and display what they would look like in an html page?
... without an associated (X)HTML file?
If what you need to do involves CSS with no knowledge of its associated (X)HTML document's structure or classes or ids... then isn't it simple enough to just write up a small page and preview it in a browser?
Not to offend, but personally I think previewing CSS without an (X)HTML document is a little strange. A few reasons:
If you start with CSS you may try to make your HTML cater to your CSS when it should be the other way around.
Starting with the CSS and then writing your page feels like a good way to end up with messy HTML, and if I have to choose between (messy HTML and clean CSS) or (clean HTML and messy CSS) I personally would choose the clean HTML every time.
You also mention targeting <div> and <span>. This is a personal opinion, but I feel pretty strongly that people shouldn't target <div> and <span> without class or id attributes. Since <div> and <span> don't have semantic meaning, I just can't imagine why you'd need to style them unless you were either CSS resetting or fullfilling a requirement, and is your customer more likely to ask for "all employee names should be underlined" or "spans should be underlined"?
... but once you're targeting class and id, you need your HTML document to go with your CSS.
While this will not autogenerate anything from your css, this is an excellent XHTML test page that includes all of the standard tags, page, and form elements you are likely to have used. Apply your style sheet to this page and you will be 80% of the way there. Then just add areas for your custom classes, etc. http://snipplr.com/view/8121/html-test-page-for-css-style-guide
TopStyle does that with an internal view. It is an excellent tool.
http://www.topstyle4.com/
Try rendur: http://rendur.com/
I agree with Richard that you shouldn't expect much if you're styling raw div and span elements. :)

Resources