215

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" />
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
ChessWhiz
  • 4,656
  • 3
  • 26
  • 40
  • 3
    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? – yu_ominae Nov 07 '12 at 04:39
  • 3
    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 anywhere, I use a nearby – Kzqai Nov 22 '13 at 18:57
  • 4
    @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. – BryanH Aug 23 '14 at 21:09
  • 3
    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. – Dave Becker Mar 13 '17 at 11:02

20 Answers20

228

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.

David
  • 72,686
  • 18
  • 132
  • 173
  • 18
    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. – Kzqai Nov 22 '13 at 19:02
  • 15
    Another scenario when it's not only okay to use inline styling, but the only way to style anything: HTML emails. – Christophe Marois Mar 11 '16 at 19:26
  • 2
    I wonder if this still holds true in today's HTML-as-an-assembly-language world? – skygate Jan 03 '22 at 11:58
76

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.
m3kh
  • 7,881
  • 2
  • 31
  • 37
vijay.shad
  • 2,444
  • 6
  • 27
  • 33
  • 2
    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! – ganders Jul 25 '14 at 13:11
  • 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 Jul 25 '16 at 11:26
  • @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. – Dariux Jan 07 '18 at 15:17
  • usually css file is trivia in size compared to the rest of the files – MartianMartian Jan 25 '22 at 00:51
33

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.

Kzqai
  • 22,588
  • 25
  • 105
  • 137
27

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

Danield
  • 121,619
  • 37
  • 226
  • 255
20

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?

issa marie tseng
  • 3,194
  • 22
  • 20
16

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...

Community
  • 1
  • 1
Bruno Jennrich
  • 360
  • 5
  • 5
  • 10
    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. – koriander Sep 23 '15 at 08:20
13

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.

BryanH
  • 5,826
  • 3
  • 34
  • 47
Sylvain
  • 3,202
  • 5
  • 27
  • 27
  • 3
    +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 :) – Tim Post Apr 10 '10 at 06:30
  • 1
    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! – Shadoweb Jul 25 '16 at 11:29
  • 1
    @Shadowbob that's what sourcemaps are for. http://thesassway.com/intermediate/using-source-maps-with-sass – Mike Chamberlain Aug 27 '17 at 15:08
  • @TimPost there's a reason why the "inspect element" feature was born – Norielle Cruz Apr 12 '19 at 09:42
12

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".

8

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.

aegatlin
  • 1,711
  • 1
  • 13
  • 7
  • 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. – Tim Schmelter Mar 09 '21 at 08:58
  • 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:..." – Majte Jan 19 '22 at 17:39
  • I've heard (and had to deal with) the fact that in-line css violates the CSP security policy, but it's still very unclear _why_ that's a policy in the first place. What could policy be dangerous about in-line css? – Matt Apr 19 '23 at 16:01
6

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.

Noah Beach
  • 61
  • 1
  • 1
5

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. :-)

Community
  • 1
  • 1
Ashish Gupta
  • 14,869
  • 20
  • 75
  • 134
3

Even if you only use the style once as in this example you've still mixed CONTENT and DESIGN. Lookup "Separation of concerns".

Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
2

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>
csvan
  • 8,782
  • 12
  • 48
  • 91
2

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.

2

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.

Anthony
  • 13,434
  • 14
  • 60
  • 80
  • 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. – Dima Apr 08 '22 at 20:14
1

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.

  • 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 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 – DOfficial Aug 24 '17 at 20:53
1

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.
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
0

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.

Diptendu
  • 2,120
  • 1
  • 15
  • 28
  • 3
    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. – Andrew Barber Nov 26 '14 at 19:24
  • 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 https://developer.yahoo.com/performance/rules.html which says 60-80% of the users come to your site daily with an empty cache (http://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. – Diptendu Nov 26 '14 at 19:31
  • 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. – astex Jan 19 '15 at 21:16
  • 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. – Diptendu Feb 15 '15 at 12:51
0

In addition to other answers, you cant target the pseudo-classes or pseudo-elements in inline CSS

Sushmit Sagar
  • 1,412
  • 2
  • 13
  • 27
0

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.