CSS semantics; selecting elements directly or via order - html

Perhaps this question has been asked elsewhere, but I'm unable to find it. With HTML5 and CSS3 modules inching closer, I'm getting interested in a discussion about the way we write CSS.
Something like this where selection is done via element order and pseudo-classes is particularly fascinating. The big advantage to this method seems to be complete modularization of HTML and CSS to make tweaks and redesigns simpler.
At the same time, semantic IDs and classes seem advantageous for sundry reasons. Particularly, direct linking, JS targeting, and shorter CSS selectors. Also, it seems selector length might be an issue. For instance, I just wrote the following, which would be admittedly easier using some semantic HTML5 elements:
body>div:nth-child(2)>div:nth-child(2)>ul:nth-child(2)>li:last-child
So what say you, Stack Overflow? Is the future of CSS writing focused on element order and pseudo-classes? Or are IDs and classes and the current ways here to stay?
(I'm well aware the IDs and classes have their place, although I am interested to hear more ways you think they'll continue to be necessary. I don't want to misrepresent this or frame it as "Are pseudo-classes ID killers?" The discussion I'm interested in is bigger-picture and the ways writing CSS is changing.)

I think that's an unreadable abomination which will mysteriously stop working when the HTML changes.
Order-based selectors are completely non-self-documenting.
If someone else takes over the project, and the HTML changes, he will have no idea what the selector is supposed to select, and will be hard-pressed to fix it correctly.
This is especially important if any part of the HTML is automatically generated.

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

Differences in query algorithms between XPath and CSS

I'm wondering why someone would want to use CSS selectors rather than XPath selectors, or vice-versa, if he could use either one. I think that understanding the algorithms that process the languages will resolve my wonder.
There's a lot of documentation on XPath and CSS selectors individually, but I've found very few comparisons. Also, I don't use CSS selectors that much.
Here's what I've read about the differences. (These three references discuss the use of XPath and CSS selectors in Selenium to query HTML, but my wonder is general.)
XPath allows traversal from child to parent
CSS selectors have features specific to HTML
CSS selectors are faster when you're using Internet Explorer in Selenium
It looks like CSS selection algorithms are somehow optimized for HTML, but I don't know how.
Is there a paper on how CSS and XPath query algorithms work and how they differ?
Are there other abstract differences between the languages that I'm missing?
The main difference is in how stable is the document structure you target:
XPath is a good query language when the structure matters and/or is stable. You usually specify path, conditions, exact offset... it is also a good query language to retrieve a set of similar objects and because of that, it has an intimate relationship with XQuery. Here the document has a stable structure and you must retrieve repeated/similar sections
CSS selectors suits better CSS stylesheets. These do not care about the document structure because this changes a lot. Think of one CSS stylesheet applied to all the HTML pages of a website. The content and structure of every page is different. Here CSS selectors are better because of that changing structure. You will notice that access is more tag based. Most CSS syntax specify a set of elements, attributes, id, classes... and not so much their structure. Here you must locate sections that do not have a clear location within a document structure but are marked with certain attributes.
Update: After a closer look to your question I realized that you are more interested in the current implementation, not the nature of the the query languages. In that case I cannot give you the answer you are looking for. I can only suppose that the reason is still that one is more dependent on the structure than the other.
For example, in XPath you must keep track of the structure of the document you are working on. On the other hand CSS selectors are triggered when a specific tag shows up, and it usually does not matter what came before it. I can imagine that it will be much easier to implement a CSS selector algorithm that work as you read a document, while XPath has more cases where you really need the full document and/or strict track of what it is reading (because the history and background of what you are reading is more important)
Now, do not take me too serious on my update. I am only guessing here because I had some background on language parsing, but I actually do not have experience with the ones designed for data querying.

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.

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.

Is using the style attribute frowned upon?

As someone who is beginning to make a transition from table based design to full CSS I'm wondering if using the style attribute to make adjustments to elements is considered "cheating" and if absolutely ALL presentation should be strictly in the style sheet?
See also:
A question of style - approaches to styling and stylesheets
There are cases where you know for sure that all you want to do is tweak the style of this one specific element, and nothing else.
In those cases you can happily use an inline style attribute. But then, at some point in the future, you'll realise that in fact you need to apply the same style to something else, and you'll realise you were wrong.
Been there, done that. 8-)
I feel there's an aspect that has not been touched upon here: the distinction between hand-edited HTML snippets and generated HTML snippets.
For human editing, it's probably better and easier to maintain to have the styles in a file.
However
As soon as you start generating HTML elements, with server-side scripts or with some kind of JavaScript, be sure to make all styles required for basic functionality inline!
For example, you wrote some kind of JavaScript library that generates tooltips. Now, you will inject DIVs into your page, that will need some styles. For example, position: absolute and, initially, display:none. You may be tempted to give these elements the class .popup and require that this class has the correct definitions in some CSS file. After all, styles should be specified in the CSS file, right?
You will make your JavaScript library very annoying to reuse, because you can no longer simply copy and invoke one .js file and be done with it. Instead, you will have to copy the .js file, but also have to make sure that all styles required by the script are defined in your CSS file, and you have to go hunting for those, and make sure their names don't conflict with classes you already have.
For maximum ease of use, just go ahead and set the required styles directly on the element as you create it. For styles that are purely for aesthetical purposes, such as background-color, font-size and such, you can still attach a class, to give the consumer of your script an easy way to change the appearance of your script elements, but don't require it!
You can use the style attribute, but the point of using CSS is that you make a change in a single file, and it affects the entire site. Try to avoid it as much as possible (old habits die hard)
It's not maintainable. All of us have done it. What you're best to do is put every adjustment into a style. Let me teach you something most developers do not know about CSS ... you can use N styles at a time.
For example, imagine you have a great style for colorized divs called someDIVStyle:
.someDIVStlye
{
background-color: yellow;
...
}
You want to use it, but just want to adjust the background-color to blue. Many people would copy/paste it and then make a new style with the change. However, simple create a style like this:
.blueBackground
{
background-color: blue;
}
Apply it as such:
<div class="someDIVStyle blueBackground">...
The style furthest to the right always overrides the properties of the styles preceding it. You can use a number of styles at once to meet your needs.
I agree with some other posters that it is best to keep the style information in the stylesheet. CSS tends to get complicated quickly, and it is nice to have that information in one place (rather than having to jump back and forth from HTML to stylesheet to see what styles are being used).
A little off-topic tip: Pressing F12 in IE8 brings up a great tool that lets you inspect the styles of elements in web pages you're browsing. In Firefox, FireBug does the same thing. Those kinds of tools are lifesavers if you want to know how a style change will affect an element.
It's a very "personal" question, to me the word "ALL" is a very strong word. You should do your best to have most of the styling in your css. but you can use style occetionally if it makes your life easier.
Generally it is best to have styles on the style sheet especially if it will be used multiple times, but using the style attribute is definitely not "cheating". A quick look through the stackoverflow source shows many examples of this.
Yes, it's kind of cheating, but it's up to you if you want to cheat a little. :)
The fundamental idea of having the styles in a style sheet is to separate the content from the layout. If you use the style attribute you are still mixing layout within the content.
However It's not that terrible, as you can quite easily move the style into a class. It's quite handy during development to be able to set a style on a specific element so easily without having to make up a class name and worry how the style will cascade.
I sometimes let the style attribute go through in the production code, if it's something that is specific for just one page, and if it's doubtful that it will be there for long. Occationally just because I am pressed for time, and it can be cleaned up later on...
So, even if you use a style attribute sometimes, you should still have the ambition that all the styles should be in a style sheet. In the long run it makes the code easier to maintain.
As others have said, in general, no.
However, there are cases where it makes perfect sense. For example, today I had to load an random background image into a div, from a directory with an unknown # of files. Basically, the client can drop files into that folder and they'll show up in the random background image rotation.
To me, this was a clear reason to dynamically build up the style tag on the div.
In addition, if you're using, for example, the .net framework with webforms and built-in controls then you'll see inline styles used anyway!
There can be very good reasons to put style information in a specific page.
For example, if you want to have a different header background on every page (travel agencies...), it is far easier to put that style information in that specific element (better, in the head of the document...) than to give that element a different class on every page and define all those classes in an external style-sheet.
The style attribute does have one important use: setting style programmatically. While the DOM includes methods to manipulate style sheets, support for them is still spotty and they're a bit heavyweight for many tasks, such as hiding and showing elements.
Yes, the style attribute is frowned upon in general. Since you're moving to the CSS method from table-based, I'd strongly recommend that you avoid inline styles. As a previous poster pointed out: bad habits are hard to break and getting into the habit of using inline styles for their temporary convenience is a mistake. You might as well go back to using the font tag. There's really no difference.
Having said that, there are occasions where it makes sense to use a simple inline style, but first develop the habit of using stylesheets. Only when you're comfortable with putting everything in a stylesheet should you start looking at shortcuts.
I think that's the general consensus of everyone who posted an answer