What's so bad about in-line CSS?
Asked Answered
A

21

219

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" />
Airminded answered 10/4, 2010 at 6:22 Comment(4)
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?Griz
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).Colangelo
@Griz - 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.Wetterhorn
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.Herculaneum
A
229

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.

Android answered 10/4, 2010 at 6:26 Comment(3)
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.Colangelo
Another scenario when it's not only okay to use inline styling, but the only way to style anything: HTML emails.Luxemburg
I wonder if this still holds true in today's HTML-as-an-assembly-language world?Absorptance
C
77

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.
Chipmunk answered 10/4, 2010 at 6:30 Comment(4)
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!Tremblay
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!Brittenybrittingham
@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.Andris
usually css file is trivia in size compared to the rest of the filesTakakotakakura
C
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.

Colangelo answered 22/11, 2013 at 19:13 Comment(0)
M
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

Matchmaker answered 9/7, 2014 at 9:24 Comment(0)
Z
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?

Zink answered 10/4, 2010 at 6:28 Comment(3)
"always, always win" - unless !important is used in the stylesheetMew
I live under the assumption that people are humane and do not use such monstrosities. =)Zink
@JamesWestgate until someone uses !important in the inline css to override the override....Colangelo
P
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...

Piscine answered 21/12, 2013 at 2:52 Comment(1)
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.Dorree
A
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.

Ankylose answered 10/4, 2010 at 6:25 Comment(4)
+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 :)Sulphuric
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!Brittenybrittingham
@Shadowbob that's what sourcemaps are for. thesassway.com/intermediate/using-source-maps-with-sassCruise
@TimPost there's a reason why the "inspect element" feature was bornLallygag
R
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".

Roca answered 10/4, 2010 at 6:28 Comment(1)
I'll pay you 5 bucks to submit "Inline CSS Styles Considered Harmful" to the ACM.Stella
A
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.

Algid answered 26/8, 2020 at 23:55 Comment(3)
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.Outgroup
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:..."Powered
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?Orelia
D
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.

Demimonde answered 11/11, 2011 at 17:35 Comment(0)
P
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. :-)

Pocketknife answered 10/4, 2010 at 6:27 Comment(0)
O
3

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

Obliquely answered 10/4, 2010 at 6:28 Comment(0)
L
3

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>
Lacombe answered 12/5, 2016 at 15:1 Comment(0)
L
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.

Lindblad answered 18/12, 2016 at 1:28 Comment(0)
P
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.

Powder answered 22/3, 2022 at 20:52 Comment(1)
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.Twine
L
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.

Liege answered 4/12, 2016 at 13:26 Comment(1)
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 answerPokey
S
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.
Springbok answered 19/2, 2018 at 1:21 Comment(0)
E
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.

Evieevil answered 26/11, 2014 at 18:38 Comment(4)
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.Weigh
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.Evieevil
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.Nydia
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.Evieevil
V
0

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

Victorvictoria answered 10/2, 2020 at 12:54 Comment(0)
S
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.

Swindle answered 22/7, 2020 at 1:39 Comment(0)
P
0

I think it's worth noting that you're exploring the idea of co-locating style with the element with the benefit of improving readability. This is not a recommendation for Tailwind (t3.gg has a video about his Tailwind journey which is interesting), but whatever you think of it, it certainly does make an art-form out of this. Your example would become:

<img src="myimage.gif" class="float-right" />
Paxton answered 25/2 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.