CSS Selectors with empty Declaration - will the browser still search? - html

Say there are selectors in a stylesheet that have no style info in them, so they are effectively empty (have no style declarations):
.main-menu {}
Will the browser still search for them?
My gut feeling is that it will depend on the browser, so an 'intelligent' programmer would say 'if selector empty don't bother' but not all browsers will have this kind of enlightened implementation. Had a quick search and couldn't find anything, was wondering if anyone on here knew anything regarding this...
Best practice i'm sure is to not have selectors with empty declarations, as they are a waste of space and time, does W3 say anything about this?
Thanks!

As a matter of fact, having empty CSS rules can actually serve to work around some bugs in certain browsers, and cause bugs in others. So there is evidence to suggest that, for at least two independent implementations anyway, the parser does not outright ignore CSS rules with empty declaration blocks.
As for best practice? Leave them out as all they would normally do is take up unnecessary bytes, and if you have a very good reason to use them, it's not a bad idea to add a comment explaining their purpose.

Related

Dynamic inline CSS. Is it advisable?

A while ago I came across this SO question:
CSS set background-image by data-image attr
If I understand the question correctly, the OP needed the ability to set an attribute on certain HTML elements and make the accompanying CSS interpret it as a URL to the background image of such elements.
I had recently faced a similar situation, where the background image of an element that had until then been static was changed into getting a variable image from a database. I considered several options but, among them, replacing the affected element with an <img> element had several undesired side effects and building dynamic .css files seemed an overkill, so I tried using a custom data- attribute and CSS's attr() function to bind it to the element's background-image, but it did not quite work due to the then limited implementation of attr() among different browsers.
In my case, I ended up deciding that a background image served from a database was content rather than design and took the approach that seemed easiest, given that browsers have supported inline CSS styles for quite a while now: I applied all non-variable styles as a rule on a separate stylesheet but I kept the variable background-image as an inline style in the element where it needed to be applied.
Since none of the answers posted to the question I am referring to suggested the usage of inline CSS styles, I did so myself and my answer has since been downvoted several times without a hint of reasoning regarding why. I understand that downvotes needn't be justified and I am happy with that, but I am worried about not seeing some obvious caveats that are waiting to bite me when I least expect it.
I have read SO threads What's so bad about in-line CSS?, using inline css - a no-no or okay in certain situations? and Inline styles vs styles in CSS, as well as some external discussions such as https://teamtreehouse.com/community/when-is-inline-css-a-good-idea and https://www.thoughtco.com/avoid-inline-styles-for-css-3466846 with respect to the usage of inline CSS, and from them I gather more or less the following:
Inline CSS is a maintenance nightmare.
It is a "best practice" separating content from design.
Inline CSS seems to be almost OK when prototyping.
Inline CSS is a necessary evil when building HTML emails.
I think I understand the arguments given in those discussions, but none of them seem to consider cases of dynamic inline styles being applied, so they do not effectively address my scenario. Based on my own experience,
That particular piece of maintenance has become trivial, since the value comes from a relational database, which has enabled us to provide things like user-customizable backgrounds without ever revisiting the source files.
It is an even better practice to analyse each scenario individually and apply the specific solutions that provide the greatest benefit at the lowest cost, regardless of what "best practices" guides may say about general scenarios.
I personally do not use inline CSS for prototyping because the browsers' development tools keep track of my changes when they are applied on a separate file but not when I define them inside the HTML block.
HTML emails make me shiver.
Nevertheless, I would really like to know why is this such a bad idea. In what ways can I expect this decision (using inline CSS to set the background-image style of an element to a value coming from a database) will come back to haunt me?
Thanks

Is it OK to use unknown HTML tags?

Correct me if I'm mistaken, but AFAIK, unknown HTML tags in markup (i.e. tags not defined in the HTML spec, like say, <foobar>) will eventually be treated as a regular <div> in an HTML 5 browser environment.
I'm thinking: how supportable is this practice? I mean, if I use unknown HTML tags in my markup, what pitfalls can I expect? Will a velociraptor pounce on me within the next few seconds?
The reason I ask is that if these tags defer to <div>, I can potentially use these tags in a more semantic manner than, say, assigning class names that identify modules. Have a look at this article, for example, of a .media class. Now what if instead of writing up that CSS to target .media, I make it target <media> instead? In my opinion, that makes the markup much more readable and maintainable, but I do acknowledge that it's not "correct" HTML.
EDIT
Just to be transparent, I did find this SO question from a few years back. It's been closed as off-topic, but I feel that I have a valid point in my own wording. It's a close duplicate, I admit, but it's from a few years back, so there might have been changes in the general environ of opinions across web developers about the topic.
user1309389 had a very good answer, and I agree with the appeal to the spec. But I disagree with their conclusion, and I think they're wrong about made-up elements leading to "undefined behaviour". I want to propose an alternative way of thinking about it, rooted in how the spec and browsers actually handle made-up elements.
It's 2015, we're on the verge of the CustomElement spec being widely adopted, and polyfills are readily available. Now is a great time to be wondering about "making up your own elements". In the near future, you'll be able to create new elements with your own choice of tag and behaviour in a fully standard and supported way that everyone can love. But until this lands in all browsers, and until the majority of people are using supporting browsers, you can take advantage of the hard work of the Polymer or X-Tags projects to check out the future of custom elements in a nearly-standard and mostly-supported way that quite a few people can love. This is probably the "right thing" to do. But it doesn't answer your question, and frankly I find "just use X" or "don't do X" to be less helpful than "here's how the spec covers this, and here's what browsers do". So, here's what I love.
Against the heartfelt recommendation (and sometimes screaming) of much of the web dev community, I've been working with "made-up" elements for the past year, in all of my production projects, without a polyfill, and I've had no unsolvable issues (yet), and no complaints. How? By relying on the standard behaviour of HTMLUnknownElement, the part of the W3C spec that covers the case of "made-up" elements. If a browser encounters an unrecognized HTML element, there is a well-defined and unambiguous way that it should be handled, and HTMLUnknownElement defines that behaviour, and you can build on top of that. HTMLUnknownElement also has to be powerful and correct enough to "not break the web" when encountering all the tags that are now obsolete, like the <blink> tag. It's not recommended that you use HTMLUnknownElement, but in theory and in practice, there's absolutely no harm in doing so, if you know what you're doing.
So how does HTMLUnknownElement work? It is just an extension of the HTMLElement interface, which is the standard interface underlying all HTML elements. Unlike most other elements however, HTMLUnknownElement doesn't add any special behaviour — you get a raw element, unadorned with any special behaviour nor constraining rules about use. The HTMLDivElement interface works almost exactly the same way, extending HTMLElement and adding almost no additional behaviour. Put simply, making up your own element is almost identical to using a div or span.
What I like about "making-up" elements is the change of mindset. You should use or invent HTML elements based on several factors, ranging from how clear it makes the markup to read, to how the browser and screen readers and search engines parse your code, to how likely your code is to be "correct" by some objective measure. I sparingly use made-up elements, but I use in exactly the way Richard described, to make things more meaningful for the author of the HTML, not just meaningful to a computer service that extracts metadata. When used in a consistent way across a team, there can be a big benefit since made-up elements can concisely express what they're for.
I particularly like using made-up elements to indicate when I will be using JS to define extra behaviour for an element. For instance, if I have an element that will have children added/removed by JS, I will use a made-up element as a clue that this element is subject to special behaviour. By the same token, I don't use a made-up element when a standard element will suffice. You will see <dynamic-list> live happily next to <div> in my code.
Now, about those pesky validators. Yes, using made-up elements isn't "valid" in the sense that it won't pass a "validator". But many commonly used features, patterns, and systems of modern HTML and JS development fail all the W3C validators. The validators aren't the law — the spec is. And the law isn't binding — the implementations in all the browsers are. The utility of validators has been dimishing for years as the flexability of HTML has been increasing, and as browsers have shifted in their relationship to the spec. Validators are great for people who aren't comfortable with HTML and need guidance. But if you're comfortable taking your guidance from the spec and from browser implementations, there's no reason to worry about being flunked by the validator. Certainly, if you follow many of the guidelines offered by Google, Apple, Microsoft, etc, for implementing any experimental features, you'll be working outside the bounds of the validator. This is absolutely an okay thing to do, so long as you're doing it deliberately and you know enough about what you're doing.
Therefore, if you're going to make up your own elements and rely on HTMLUnknownElement, don't just treat it like a wild west. You need to follow a few simple rules.
You have to use a hyphen in the name of your tag. If you do, you are guaranteed to never collide with a future edition of the HTML spec. So never say <wrong>, always say <quite-right>.
Made-up elements can't be self-closing — you have to close them with a closing tag. You can't just say <wrong> or <still-wrong />, you have to say <totally-good></totally-good>.
You have to define a display property for your element in CSS, otherwise the rendering behaviour is undefined.
That's about it. If you do these things, you should be good to use made-up elements in IE9 and up, relying on the safety net of the HTMLUnknownElement. For me, the benefits far, far outweigh the costs, so I've been using this pattern heavily. I run a SaaS site catering to major industrial corporations, and I've had no trouble or complaints thus far. If you have to support older versions of IE, it's wise to stay far away from any "2015" technology or their crude approximations, and stay safely within the well-trodden parts of the spec.
So, in summary, the answer to your question is "yes, if you know what you're doing".
You should always approach HTML as it is defined in its respective specification. "Defining" new tags is a bit of an extreme approach. It might pass a browser check because it implements various failsafes, but there is no guarantee of this. You're entering the land of Undefined Behaviour, at best. Not to mention you will fail validation tests, but you seem to be aware of that.
If you wish to be more semantically expressive in your markup, you can use HTML5 which defines quite a bit of more descriptive tags for describing the structure of your page instead of generic divs which need to be appended ids or classes.
In the end, a short answer: No, it's bad practice, you shouldn't do it and there could be unforeseen problems later on in your development.
No. You will fail validation, you will get random issues cross browser and you WILL be eaten by said dinosaurs. CSS is the answer if you want your page to behave predictably.
Yes We Can.
There is a new spec going on about custom elements/tag - http://w3c.github.io/webcomponents/spec/custom/.
Only issue with this is you have to use js to register your new element
You can read more about this at
https://developers.google.com/web/fundamentals/getting-started/primers/customelements
Rule #1 of browser interoperability is: don't have errors. No matter how many browsers you test in, there are always browsers you can't test, for instance because they don't exist yet.
Also, unknown elements will be treated as <span>, not <div> by most browsers currently.
If it's really source readability(*) you're after, you should look into XML+XSLT.
That way, you can use all the tag names you want, and make them behave in any way you like and you don't have to worry that <media> will be a real element in some future version of HTML.
One good real world example is the element <picture>. If a website ever used <picture> and relied on the notion that this element would have no styles or special content by itself, they are in trouble now!
(*) With XML+XSLT, the readability will be in the XML part, not the XSLT part, obviously.
Generally not recommendable, e.g. IE wont apply css-styles to unknown tags.
All other browsers render unknown tags as inline-Elements (which causes problems with nesting).
I recommend you the following article: http://diveintohtml5.info/ There is a section about unknown tags.
In my case I use a lot of them into my Webkit-powered game GUI system, and everything works.
W3C says:
HTML5 supports unknown tags as inline elements, but it recommends CSS
styling for it.
Here is the source: https://www.w3schools.com/html/html5_browsers.asp
In your example you are talking about <media>, it's could be great but if html6 adds this tag for another element, your code won't be retrocompatible.
The one downside that worries me is what if a custom tag I use now, becomes an official HTML-tag next year or even later?
Therefore how about this: Instead of custom tags use 'div' + a custom CSS-class.
CSS-classes are meant to be custom, it is definitely ok to have your own custom CSS-classes. Your div can then further have any number of CSS-classes associated with it making the semantic machinery even more flexible, you could call it multiple inheritance.
Instead of div you could use span for the same purpose. I would like to use something shorter actually, say p but unfortunately p has its own special behavior of what happens if you don't close it.
But definitely if you go the route of expressing semantics with CSS-classes then it does help to use a tag-name that is as short as possible. I wish there was something shorter than div, say for instance t for 'tag'.
By default, custom elements main parts of many JavaScript-Framwork. It is state of the art in modern javascript.:
var XFoo = document.registerElement('x-foo', {
prototype: Object.create(HTMLElement.prototype)
});
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements
https://www.html5rocks.com/en/tutorials/webcomponents/customelements/
Is it OK to use unknown HTML tags? If you ask wrong questions, you get allways wrong answers. If you define your unknown tag with javascript as a CustomeElement , your unknown tag is no longer part of the HTML5/HTML-definition.
Yes, you can use unknown tags, if you define the tag in your javascript.
What's wrong with the judicious use of < !-- your stuff here -- >. It worked for scripts back around the time of the Cretaceous–Paleogene boundary. Dinosaurs ceased to be a problem around that time, that is apart from the flying, feathered variety.
It's bad practice and you should not do it. The browser renders it as div as fallback solution in most cases but it's not valid html and therefore never will pass a validity test.

using inline css - a no-no or okay in certain situations? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Inline styles vs styles in CSS
i guess i'm looking for some opinions on this. I am all for using css styles as classes in a separate .css file. But every once in a while, i run into a scenario where i need just some padding for a particular element or change the css class' width only in one particular situation. Is it okay to add inline styles in those scenarios? do people do this or always create classes for everything.
My theory would be if its not something reusable or does not contain more than 2 styles, why create a class for it. Am I wrong in thinking that?
Summary of Answers (since there are many)
It is better to avoid inline styles because
1) style sheets provides more maintainability.
2) better separation of html data and layout.
3) re-usability of styles.
4) probably provides better caching.
Overall, css style sheet is the best practice.
Anything is reusable if you think it through and set it up correctly. Even one-line, one element CSS attributes can be beneficial if reused. This takes advantage of the concept of caching, which will keep the css in memory after the initial load hit. No matter which way you slice it, inline styles add to your overhead every load without question.
Never mind the fact that inline mixed with a proper css document adds overhead to your own debug time, figuring out where the darned calls are coming from.
Two answers to this one:
1) It's considered good practice to keep your design (css) and your data (html) separate. By adding in-line styles, it makes it more difficult to revise the look of a site, it makes it more difficult for future programmers to modify your site, and is overall NOT the best way to go.
If everything is in a CSS file(s), then you can change the entire design of your site without having to mess with the data (HTML) of the site. This is ideal.
2) Yes, a lot of people still use inline styles very often when tweaking something small, regardless of "best practice".
You said: "if its not something reusable or does not contain more than 2 styles"
I would add another reason to use external stylesheets: maintainability. If you (or someone else) has to fix your code in the future, you will have a much easier time of it if all of your styling is in one place. You will not remember that you added that little bit of styling inline, and you may spend hours hunting for it.
It is a good standard to keep all styling separate to maintain clean, maintainable code.
That said, we can acknowledge that it is "ok" to use inline styles, as you asked in your question. However, best practice is often something more than "ok" and should serve as a guide as often as possible.
I feel like a good balance is all that you need. While its typically considered better practice to create classes as much as possible, there comes a point when its just easier to use an inline style. Like you said, if there's just that one element that needs that minimal extra padding, its not a crime to give it that. At least, in my opinion it isn't. But definitely be in the habit of making classes for just about everything, except minor exceptions.
Its not just about re-use, its about getting into the habit of doing things correctly. What if someone else needed to help you on the project, they would have to sift through your whole file to find every instance of an inline style somewhere...
People who know their CSS always create a specific style rule for everything.
Thats my opinion and I believe it to be shared among my colleagues.
A big point for me is: maintenance. When all of the CSS is in external stylesheets, it is going to be relatively straightforward to find the styles your looking for to edit them. If there are inline styles, it will be harder to find what you're looking for.
I'm usually skeptical about claims that a style never be reused. If it happened once, it is likely to happen again. Coding for reusability is always a good idea and usually results in cleaner, better written code in my experience.
Even in these situations, I will usually add a unique class somewhere up in the target element's ancestors - often on the body tag - that I can use to target the the "unique situation" and keep all the CSS in the external stylesheet.
That being said, I do occasionally use inline styles. When I do, it is almost exclusively in a situation where I know that I will be animating styles with JavaScript after the page has loaded. I only do inline styles for the properties that I am going to animate and the rest go in the external stylesheet.

online CSS optimizer?

Is there an online CSS optimizer equivalent to Googles JavaScript Closure Optimizer.
I've found plenty of CSS compressors online, but I'm looking for a CSS optimizer ... where it actually removes redundant/conflicting attributes
Online tools based on csstidy: www.codebeautifier.com or www.cleancss.com.
And perhaps CSS Redundancy Checker might be useful for you. It's a Ruby script that will take CSS rules, and a set of HTML files, and will tell you what you aren’t actually using.
Personally, I wouldn't trust any CSS optimizer such as you describe. Any time I have ever tried one, and I've tried a few and even tried to write one, it has resulted in CSS problems on pages I've created.
For one to actually remove conflicting selectors, it would really have to understand how you would like such conflicts resolved — which ones are "right" and which are "wrong" — and that is something you have to eyeball to decide. Even removing "redundant" selectors is fraught with peril, unless you have repeated selectors verbatim. And any CSS hacks you have employed (not good practice, but sometimes unavoidable) can be destroyed.
I'm not saying this kind of thing is impossible, just that it's VERY hard to do and you should absolutely expect to regression-test all your pages after using one.
You could make such a service by using the relevant parts of an open source rendering engine such as WebKit or Gecko.
Infact....
CSSTIDY
never used it myself though
it is open sourced and provides you the ability to use it with php, it also uses no regular expresions so is compatible with css2
Check out Dust-me it's a firefox extension that will at least remove unused selectors. I suspect it might be a combination of these that'll get the job done.
https://csscompressor.net gives an audit of the changes it has made.
Be careful when using some hacks eg for IE6, as they may cause a failure

Writing Efficient CSS

Ok so in another question something was being discussed, and this link was mentioned:
https://developer.mozilla.org/en/Writing_Efficient_CSS
In that article, they say some things I didn't know, but before I ask about them, I should ask this... Does that apply to CSS interpreted by Firefox? Forgive my noobness, but I wasn't sure what they meant by Mozilla UI. (don't hurt me!)
If it does apply, when they say:
Avoid the descendant selector!
The descendant selector is the most
expensive selector in CSS. It is
dreadfully expensive, especially if a
rule using the selector is in the tag
or universal category. Frequently what
is really desired is the child
selector. The use of the descendant
selector is banned in UI CSS without
the explicit approval of your skin's
module owner.
* BAD - treehead treerow treecell { }
* BETTER, BUT STILL BAD (see next guideline) - treehead > treerow > treecell { }
The descendant selector is just a space? And then what would the difference be between child and descendant? Child is an element inside another, but isn't that the same as descendant? As I'm writing I think I might have figured it out. A descendant could be a child/grandchild/great-grandchild/etc? And child is only one deep?
Sorry again for the stupid level of my question... just wondering, because I have been constantly using descendants in my CSS for my site. But yeah, if this isn't about Firefox then this whole question is pointless...
If its not about Firefox, does anyone have a link to an article explaining efficiency for Firefox or Browsers in general?
A descendant could be a child/grandchild/great-grandchild/etc? And child is only one deep?
Yes, exactly. Since a child can only be one deep, there's a much smaller space that the rendering engine has to recursively search to check if the rule matches or not.
And yes, that article is about both Firefox and browsers in general. Most (all?) of what is in it applies to any page rendering engine.
First of all - the suggestions in this article are not for html pages - they are specifically for the Mozilla UI - XUL, so it may be best practice for XUL, but not for html.
Applying the CSS on an average HTML page is one of the quickest things than happen while loading the page.
Also, the article may suggest the fastest way to apply css rules, but at what cost? For example, they suggest not having more than one class per rule:
BAD - .treecell.indented { }
GOOD - .treecell-indented { }
That is almost outrageous. It may lead to quicker CSS, but who cares? Assuming you already have .treecell and .indented, following these suggestions leads to complicated logic, harder maintenance, duplicated css rules, harder JavaScript (which costs a lot more that CSS), etc.
They suggest not using the full richness of CSS selectors and replacing these selectors with flat classes, which is a shame.
...as I'm writing I think I might have figured it out. A descendant could be a child/grandchild/great-grandchild/etc? And child is only one deep?
Indeed.
One thing I can add on the efficiency side of things is: Don't use * unless you really mean it. It's pretty intensive as rules go and most people could get away just specifying the elements they really want to target.
A "parent > child" is only one step down, whereas an "ancestor descendant" could be one or more steps down.
Even better is to use "#id" tags wherever possible such that there is less DOM searching.
The UI CSS is for styling the internals of the browser - the settings dialog, extensions interfaces etc.
Descendants and children are different, children are much more specific and result in much less having to be considered.
The problem with the child selector is that it's not as well supported. Of course, this might've been fixed on newer IE browsers.
In any case, when writing CSS for a webpage it isn't going to be that big of a deal. I doubt the fractions of seconds you'd save in page load would even be noticed. This article seems more directed towards people writing stuff for the actual browser, not websites.
O'Reillys "Even Faster Web Sites" has a whole chapter on this entitled "Simplifying CSS Selectors". It references your link on Mozilla.
I think two points are worth bearing in mind.
Yes, if you did this as far as possible, your HTML and CSS would be a mess of styles and possibly even more inefficient due to added file size. It is up to the developer to pick the best balance. Don't agonize over optimizing every line as you write it, get it working then see what can be beneficial.
As another commenter noted, it takes the browser milliseconds to figure it out how to apply your styles on page load. However, where this can have much bigger impact is with DHTML. Every time you change the DOM, the browser re-applies your whole style sheet to the page. In this scenario many inefficient selectors could make a visible impact to your page (perceived lagginess/ unresponsiveness).
The documentation for Google's Page Speed (a Firefox/Firebug add-on) includes a good page on efficient CSS.