What's so bad about in-line CSS?

99,664

Solution 1

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.

Solution 2

The advantage for having a different css file are

  1. Easy to maintain your html page
  2. Change to the Look and feel will be easy and you can have support for many themes on your pages.
  3. 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.

Solution 3

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.

Solution 4

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

Solution 5

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?

Share:
99,664

Related videos on Youtube

ChessWhiz
Author by

ChessWhiz

Computer programmer, chess player, etc. Check out a small puzzle/action web game I wrote at http://bipsland.com. Let me know what you think!

Updated on March 23, 2022

Comments

  • ChessWhiz
    ChessWhiz over 2 years

    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" />
    
    • yu_ominae
      yu_ominae over 11 years
      I'm always against inline css, even for a single item, BUT I see so many commercial sites riddled with style attributes, that it makes me wonder what the accepted practice actually is?
    • Kzqai
      Kzqai over 10 years
      I think that inline styles are lazy. I say this because I do it so often myself, so I know -why- I'm doing it, because I have no idea whether the style will stay, so I used to do it right next to the html. These days, with html5 and pragmatic support for <style></style> anywhere, I use a nearby <style> tag instead while messing with layout, and then migrate it to the core/main css file after. Same benefits of speed and immediacy, almost none of the disadvantages (side effects on off-page elements due to specificity being one).
    • BryanH
      BryanH almost 10 years
      @yu_ominae - bear in mind that "commercial sites" don't always adhere to best practices; in fact is is pretty rare. The deciding factor is if the developer knows, cares and has the time; or if the manager is willing to allocate the time and direct the staff to implement. When the work priority is to meet the deadline, quality is usually decreased.
    • Dave Becker
      Dave Becker over 7 years
      Worth noting that although "commercial sites" appear to be using inline styles, this can be the result of using certain jQuery calls (e.g. css()) which apply inline styles.
  • Tim Post
    Tim Post about 14 years
    +1 - I really gripe when our designers do that as a quick fix, just to get something to line up. Using an external CSS is supposed to mean never having to do a massive text replace, unless of course operating on a single style sheet. I got a control panel template released to me yesterday and it took 2 1/2 hours to find instances where icons were tweaked with inline styles. Maddening I tell you .. maddening :)
  • James Westgate
    James Westgate about 14 years
    "always, always win" - unless !important is used in the stylesheet
  • issa marie tseng
    issa marie tseng about 14 years
    I live under the assumption that people are humane and do not use such monstrosities. =)
  • Kzqai
    Kzqai over 10 years
    @JamesWestgate until someone uses !important in the inline css to override the override....
  • Kzqai
    Kzqai over 10 years
    If I had a nickel for every time I've had to modify a image's float or some other css that was originally going to be "just for one element"... ...well, I'd go out for a dinner out at a nice restaurant.
  • ganders
    ganders almost 10 years
    I ask myself this question about every month, (fairly new to web programming) and this is the first time i've read anything about the css file being cached. That does it for me right there!
  • Andrew Barber
    Andrew Barber over 9 years
    You're missing something re: latency. A much bigger problem, really: Embedding the CSS means every page request must contain that CSS, whereas otherwise, the browser can cache it.
  • Diptendu
    Diptendu over 9 years
    You are right. That's why we inline CSS when the code size is very small so that it does not cause too much overhead on page size. There is a very interesting article on Yahoo! Perf guidelines page developer.yahoo.com/performance/rules.html which says 60-80% of the users come to your site daily with an empty cache (yuiblog.com/blog/2007/01/04/performance-research-part-2) Of course it totally depends on the popularity of the website - The more popular a site, the chances of a having a non empty cache is more.
  • astex
    astex over 9 years
    While it's likely that a user accesses your site with an empty cache, it's unlikely that they're going to access your page with an empty cache. Unless the page is single-use (i.e each user only views it once), it will perform better with a separate css file.
  • Diptendu
    Diptendu over 9 years
    These days many modern webpages are designed as Single Page Application, the full page gets loaded only the first time. Next time onwards the page is changed through AJAX call. So even if the page is multiuse the external CSS is going to get loaded only once.
  • Joshua Grosso Reinstate CMs
    Joshua Grosso Reinstate CMs almost 9 years
    I'll pay you 5 bucks to submit "Inline CSS Styles Considered Harmful" to the ACM.
  • koriander
    koriander almost 9 years
    I think this really is the correct answer. The mantra of "separation of concerns" is just one criteria. "Locality" is also important for ease of maintenance. The key aspect is whether or not the style is reusable at semantic level, not merely syntatic. If that's the case, then the sheet makes sense. E.g., I'm not going to create a class for "float:right" just because two elements use it. It dependes on the elements being semantically the same. A "color" style usually is semantically related (part of the theme), and usually would go in a sheet.
  • Christophe Marois
    Christophe Marois over 8 years
    Another scenario when it's not only okay to use inline styling, but the only way to style anything: HTML emails.
  • Shadoweb
    Shadoweb almost 8 years
    I was thinking about cache as well, but in my case I'm having to deal with merged CSS that are 15k lines, it's impossible to maintain all the big portion of junk that was only to be used once on a single page that doesn't exist anymore. So you are throwing CSS code to everybody on each visits for a single temporary page that is viewed by only 1% of your traffic. I'm not sure the internet trafic argument is valid in every cases. Fortunately Web Components are going to change things!
  • Shadoweb
    Shadoweb almost 8 years
    When you have 50+ SCSS and your Inspect element only points to the compressed CSS, I'm not sure it's CSS that wins on the simplicity!
  • DOfficial
    DOfficial almost 7 years
    Yes! this is crucial in trying to minimize the "time to first paint" if all of your css is in files it will defer the DOM until the stylesheets have been downloaded by the user. Having your critical styles in an inline <styles> node in the head you can begin to render the DOM immediately and defer the external stylesheets. Plays a big factor in ~3G connections and perceived speed. +1 for your answer
  • Mike Chamberlain
    Mike Chamberlain almost 7 years
    @Shadowbob that's what sourcemaps are for. thesassway.com/intermediate/using-source-maps-with-sass
  • Dariux
    Dariux over 6 years
    @Shadowbob - would it not be better to have smaller css files instead of big one? Have one generic maybe which is used for all pages, but then have small seperate style sheets for other pages. Should be easier to maintain. And if the trafic is problem, then for production probably can merge in to one, in the build process.
  • Norielle Cruz
    Norielle Cruz about 5 years
    @TimPost there's a reason why the "inspect element" feature was born
  • Tim Schmelter
    Tim Schmelter over 3 years
    True, and if you have to enable this CSP you have a lot of work to provide the nonce values or to remove the inline styles and replace them with CSS.
  • skygate
    skygate over 2 years
    I wonder if this still holds true in today's HTML-as-an-assembly-language world?
  • Majte
    Majte over 2 years
    That has exactly happened to me sadly and I learned my lesson. I needed to rewrite much of my code to get my application run with a CSP policy and without running into browser errors. "Refused to execute inline script because it violates the following Content Security Policy directive:..."
  • MartianMartian
    MartianMartian over 2 years
    usually css file is trivia in size compared to the rest of the files
  • Dima
    Dima about 2 years
    This approach improves "clarity of code" only for the one who is writing it. Inline styles have a high specificity and will make it hard to control the UI from spreadsheets and make global changes. In large teams, CSS coders will need to go through the code to fix issues or improve UI. They may not have the knowledge to do so, or not be able to set up the env., or compile the app to verify the changes. Plus, the whole app needs redeployment. This approach also promotes one-off styles/one-liners (instead of focusing on creating UI design systems) which will eventually make the UI inconsistent.