Dynamic inline CSS. Is it advisable? - html

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

Related

Writing HTML code for future-proof CSS

Looking at the CSS Zen Garden, I can see how powerful and convenient it is to separate design and content. The possibilities seem nearly endless. One can change the style sheet and the appearance of the whole site can be drastically altered.
Let's say I'm putting together the HTML part of a website. How do I know where to put divs, where to nest them, etc?
For example, let's say I want to centre something on the screen: I would generally nest 3 divs together: one display:table, one display:table-cell, and one margin-left:auto;margin-right;auto which would have the content.
Let's say I'm just doing the HTML content, but am not thinking about the design at this stage. How would I know that I need to nest together 3 divs if I don't necessarily know I will centre it on the screen?
Or if I have one design now with HTML/CSS and I have my divs and spans all set out, what happens in 18 months if I decide to change the CSS for a completely new layout? Sometimes I will have extra divs and sometimes I won't have enough.
Presumably it would always be better to have more levels than not enough. That way, the worst thing that can happen is that you have a few superfluous divs which aren't styled and have no visible effect.
Is this generally a problem others have? I know CSS Zen Garden is a special case, but would you generally change the HTML code considerably when you change the corresponding CSS?
I've worked in web development for many years, and over here in Reality things are a bit different from Theory: There is no such thing as separation of content and presentation. You'll always end up sliding in additional divs.
You better follow the YAGNI principle. Don't worry about your CSS as you're writing your HTML. Come back later and do the neccessary adjustments.
As for Zen Garden, you'll find a comment in the source code:
This xhtml document is marked up to provide the designer with the maximum possible flexibility. There are more classes and extraneous tags than needed, and in a real world situation, it's more likely that it would be much leaner.
Theoretically, in order to change the style, you wouldn't have to touch the data (HTML). In practice, there are those problems you mentioned.
What I would do is a more-or-less sensible usage of divs (so for example, anything I think that I might want to move around, or any bunch of HTML that I would want to refer to together - would go in a div of its own). Otherwise, don't use too many divs, for reasons such as readability, maintainability, and size of HTML.
Then, whenever you want to change the style, make the minimal addition of divs so that you'll be able to do what you want.
This is a genuine problem with CSS and it was recognised by the authors of CSS3. The most recent published draft (2003) of the CSS Generated and Replaced Content module discusses a pseudo element called ::outside which would have solved the problem you describe. It would, when implemented, for
<div class="mycontent">Some text</div>
have allowed you to write:
div.mycontent { margin-left:auto;margin-right:auto; }
div.mycontent::outside { display:table-cell; }
div.mycontent::outside(2) { display:table; }
Unfortunately, the ::outside pseudo-element never made it into the CSS3 selectors spec, and the next draft (2011) of the CSS Generated and Replaced Content module will not mention the ::outside pseudo-element.
So we're stuck with putting wrapper divs everywhere just in case which as you note, does not allow proper separation of presentation and content, and remains a deeply unsatisfactory situation.
It all depends on how your website is driven. If you are using template files, the amount of updates will be minimal.
You do not want to overload your code with superfluous Divs because a) load time (althought it will be minimal difference in theory) and b) because it will create a lot of confusion when others edit your files.
From your example, it looks like you may be used to table style layouts. Using Divs to contain your layout will make flexibility very easy.

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.

Html/ css coding standards

I'm building my first website for an internship. My instructors always told me to never embed any styles on my html page.Now that I'm actually creating a site I find it annoying that, if I want to change the color of my font for a span tag - I have to I.D. it and reference it in a css file. Is there some other reason then organizational purposes for using CSS? Would embedding a single style be such a convention breaker? Thanks for reading this and I'd appreciate any feedback.
There are a couple of reasons.
Times when you want to change the style of a single element on a single page should be exceedingly rare, so it shouldn't be such a hardship. Any other time, it is going to be more efficient (from an HTTP caching perspective) and easier to maintain (from a separation of style and structure perspective) to externalize the style information.
Since there is a good chance that you'll want to style it differently for different media (e.g. screen and print), you'll need a proper stylesheet for that too.
If you embedd a style to several HTML pages, and want to change it later, you have to go file by file changing it. That is one good enough reason for me.
The key word here is maintainability. Organized code is maintainable code! It is far better to add an id to a tag and reference it in the global css file than to do it inline, because if you want to change that style later, you know where to find it, and you only have to change it in one place.
The reason you want to offload the CSS into a different file is so the browser can cache it. Otherwise, the browser has to load all the CSS as well as all the markup on every page. If you keep it in a separate file, the browser only has to load the CSS once.
The basic argument for this is that HTML's purpose is to provide structure while CSS's job is to provide styling, by embedding CSS in HTML you're breaking this basic rule. Plus, you'll have a tough time in maintaining pages.
Ideally, a design should be consistent enough that you can use generic rules for such situations. If you want to emphasize something, then <em> or <strong> is likely the way to go. After styling your <em> or <strong>, you can easily add the same emphasis to other areas of the site.
It's not simply about performance or style, it's also about consistency and ease of maintenance.
Find the similar elements in your design and mark them up similarly. It's as easy as that.
Even if it's "just 1" you should still do it because it helps you get in the habit of it.
embedded css has the following problems:-
1. It has browser compatibility problem. Example Ie has problem understanding inbuilt styling.
2. If you want to use the same css style again , it is better to have a class for it.

CSS semantics; selecting elements directly or via order

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.

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