What's the difference between inline styles vs classes?
Asked Answered
C

11

47

In my head, I've always known to use classes over inline styles for any project. But are there any effective differences between the two?

Cradle answered 29/6, 2010 at 16:29 Comment(0)
G
34

There is a simple reason. The point of CSS is to separate the content (HTML) from the presentation (CSS). It's all about accessibility and code reuse.

Goodrum answered 29/6, 2010 at 16:34 Comment(2)
+1 it all comes down to reuse. But sometimes inlining a style which has little or no potential for reuse can help reduce clutter in the library of classes that are actually worth reusing.Marvin
Then there's the speed/size advantages. An external CSS file can define redundant formatting rules, sometimes drastically cutting down the size of your HTML. And an external CSS file can be downloaded once and cached for the duration of the user's visit.Babushka
A
41

First of all:

  • If the HTML is built or generated independent of the overall site design (e.g. shared template code), then add reasonably-named classes and IDs, linked exclusively to external stylesheet(s). Use sufficient elements to allow for arbitrary CSS manipulation. For example, see the CSS Zen Garden. This applies to ALL CMSes, programs, scripts, and other dynamically-generated site content. The HTML output must contain absolutely no styling or layout of any sort at all. No exceptions.

Assuming you're dealing with static content, then:

  • If there's any way you can reuse the style, make it a class and link to a stylesheet.

  • If there's no way would ever reuse the style (it's a one-off thing that doesn't make sense anywhere else) then use a <style> block that references the element's #id.

  • If the CSS attribute only makes sense in the context of the surrounding HTML (e.g. some usages of clear:) then I inline the style into the element.

A lot of people call this heresy, just like a lot of people denounce any use of goto in modern programming languages.

However, rather than subscribing to stylistic dogma, my view is you should choose the method based on your circumstances that decreases your overall workload the most. Stylesheets add a level of indirection that makes site-level changes easy and helps build consistency. But if you have several dozen classes on each page that are only used in one place, then you're actually increasing your workload, not decreasing it.

In other words, don't do something dumb and confusing just because people tell you it's the right way to do it.

Analyse answered 30/6, 2010 at 1:10 Comment(4)
I mainly agree to these points, but if you take it a point further: why not ditch the style block and ids (point #3) - and instead just use inline for these elements? First of all this means you don't have to add useless id's to tags that don't need them anyway, and you decrease your workload by not having to jump around in the document. Besides that I don't see what it really adds anyway :)Boggers
I think point #3 may be speculating that it's possible/probable that you create or run into another spot where the style may be used in the future and can swap out the ID for a class at that time. I've had this happen a good bit in the past.Hawser
@DirkBoer, some styles can't be inlined: #1033656Cayser
@IvanRave, agreed. It's not a static rule, I'm just in favor of pragmatism :)Boggers
G
34

There is a simple reason. The point of CSS is to separate the content (HTML) from the presentation (CSS). It's all about accessibility and code reuse.

Goodrum answered 29/6, 2010 at 16:34 Comment(2)
+1 it all comes down to reuse. But sometimes inlining a style which has little or no potential for reuse can help reduce clutter in the library of classes that are actually worth reusing.Marvin
Then there's the speed/size advantages. An external CSS file can define redundant formatting rules, sometimes drastically cutting down the size of your HTML. And an external CSS file can be downloaded once and cached for the duration of the user's visit.Babushka
W
9

If the choice was there, my first preference will be classes/other selectors. However, there are situations where inline styles are the only way to go. In other situations, just a CSS class by itself requires too much work, and other types of CSS selectors make more sense there.

Suppose you had to zebra stripe a given list or table. Instead of applying a particular class to each alternate element or row, you could simply use selectors to do the job. That will keep the code simple, but it won't be using CSS classes. To illustrate the three ways:

Using only class

.alternate {
    background-color: #CCC;
}

<ul>
    <li>first</li>
    <li class="alternate">second</li>
    <li>third</li>
    <li class="alternate">fourth</li>
</ul>

Using class + structural selectors

.striped :nth-child(2n) {
    background-color: #CCC;
}

<ul class="striped">
    <li>first</li>
    <li>second</li>
    <li>third</li>
    <li>fourth</li>
</ul>

Using inline styles

<ul>
    <li>first</li>
    <li style="background-color: #CCC">second</li>
    <li>third</li>
    <li style="background-color: #CCC">fourth</li>
</ul>

The second way looks the most portable and encapsulated to me. To add or remove stripes from any given container element, simply add or remove the striped class.

However, there are cases where inline styles not only make sense, but are the only way to go. When the set of possible values is huge, it will be stupid to try to make classes in advance for each possible state. For example, a UI that allows the user to dynamically place certain items anywhere on the screen by dragging. The item will have to be positioned absolutely or relatively with actual coordinates such as:

<div style="position: absolute; top: 20px; left: 49px;">..</div>

Surely, we could use classes for each possible position the div can take, but that's not recommended. And one can easily see why:

.pos_20_49 {
    top: 20px;
    left: 49px;
}
.pos_20_50 {
    top: 20px;
    left: 50px;
}
// keep going for a million such classes if the container size is 1000x1000 px

<div class="pos_20_49">..</div>
Wahkuna answered 30/6, 2010 at 2:30 Comment(0)
T
4

Use common sense.

Everyone knows that presentation and content should, in an ideal world, be separated. Everyone also knows that this doesn't work very well a lot of the time. We all know that you're supposed to use divs rather than tables for layout, but we also know that for any circumstance where you don't have full control over the content it just doesn't work properly.

Downloading a 500k style sheet to style one element because you've taken every possible style and stuck it in a style sheet will kill your page, downloading 500 smaller style sheets to style your page because you need them all will also kill your page.

Reuse is great in concept, but the reality is that it's only useful in certain contexts. This applies equally to pretty much anywhere the concept exists. If your project does what you want it to do, does so in every reasonable browser, does so in an efficient way, and does so reliably, then you're good to go, it's not dramatically harder to refactor css than is is code.

Trypanosome answered 30/6, 2010 at 1:25 Comment(0)
B
3

I can't think of any pros for inline styles.

CSS is all about Progressive Enhancement, and not repeating yourself (DRY).

With stylesheets, Changing the look becomes as easy as changing one line in the HTML code. Make a mistake or the client doesn't like the change? revert to the old stylesheet.

Other advantages:

  1. Your site can automagically adjust to different media, such as for printout and for hand-held devices.

  2. Conditionally-included CSS fixes, for that gawd-awful browser-that-shall-not-be-named, become a snap.

  3. Your users can easily customize the site with plugins like Stylish.

  4. You can more easily reuse or share code from site to site.

Berglund answered 29/6, 2010 at 18:32 Comment(3)
Was that meant to be "changing one line in the CSS code"? Because changing one line in HTML could change the look even if you weren't separating content from presentation.Paramo
@Chuck: No that was one line in the HTML. Changing from OldCSS_File.css to NewCSS_File.css, for example.Berglund
@Brock Adams, A pro of inline styles is definitely there with modularized applications. When modules are independent, they do not know what classes exist. Thus, they have to create their own.Acidfast
E
3

I can think of only two situations where inline styles are appropriate and/or reasonable.

  1. If inline styles are programmatically applied. For example, showing and hiding elements with JavaScript, or applying content specific styles when rendering a page (see #2).

  2. If inline styles complete a class definition for a single element in cases where id's are neither appropriate or reasonable. For example, setting the background-image of a element for a single image in a gallery:

HTML

<div id="gallery">
    <div class="image" style="background-image:url(...)">...</div>
    <div class="image" style="background-image:url(...)">...</div>
    <div class="image" style="background-image:url(...)">...</div>
</div>

CSS

#gallery .image {
    background: none center center;
}
Endotoxin answered 30/6, 2010 at 3:34 Comment(0)
B
2

With the addition of Custom properties to CSS, now there's another use case. One might want to use inline style to set custom properties.

For e.g. below i am using CSS grid to align HTML Lists and Div blocks and i wish to have flexibility in the HTML (Just the way BootStrap or any other framework provides) as this HTML is dynamically generated by application.

CSS :

:root{
--grid-col : 12;
--grid-col-gap:1em; 
--grid-row-gap:1em;
--grid-col-span:1;
--grid-row-span:1;
--grid-cell-bg:lightgray;
}

.grid{
    display: grid;
    grid-template-columns: repeat(var(--grid-col), 1fr);
    column-gap: var(--grid-col-gap);
    row-gap: var(--grid-row-gap);
}

.grid-item{
    grid-column-end: span var(--grid-col-span);
    grid-row-end: span var(--grid-row-span);
    background: var(--grid-cell-bg);
}

HTML :

    <ul class="grid" style="--grid-col:4">
        <li class="grid-item">Item 1</li>
        <li class="grid-item">Item 2</li>
        <li class="grid-item">Item 3</li>
        <li class="grid-item">Item 4</li>
        <li class="grid-item">Item 5</li>
        <li class="grid-item">Item 6</li>
        <li class="grid-item">Item 7</li>
        <li class="grid-item">Item 8</li>
    </ul>

In the above HTML to change the four columns to 3 i change the custom property using style attribute :

    <ul class="grid" style="--grid-col:3">
        <li class="grid-item">Item 1</li>
        <li class="grid-item">Item 2</li>
        <li class="grid-item">Item 3</li>
        <li class="grid-item">Item 4</li>
        <li class="grid-item">Item 5</li>
        <li class="grid-item">Item 6</li>
        <li class="grid-item">Item 7</li>
        <li class="grid-item">Item 8</li>
    </ul>

You can check the extended live example at https://codepen.io/anon/pen/KJWoqw

Briseno answered 1/2, 2019 at 10:23 Comment(0)
D
1

Assuming that you are using external stylesheets, an additional benefit on top of those previously mentioned is caching. The browser will download and cache your stylesheet once, and then use the local copy each additional time it is referenced. This allows your markup to be more compact. Less markup to transfer and parse means a more responsive feel and better experience for your users.

Daniel answered 30/6, 2010 at 0:44 Comment(3)
On the other hand, markup can be cached as well; however, caching CSS is easier since CSS is more likely to be static than HTML. Just saying.Endotoxin
@Justin: Fair point. My intent wasn't to imply that pages could not be or were not cached; my apologies if that is how it was received. My point was that CSS is typically a fairly static resource and separation buys you an effective and simple means of caching. With the dynamic nature of many pages, the options for content caching often require more planning and sophistication. However, it is fair to say that is dependant upon the complexity of the content on a given site and for static content the CSS cache benefit that I mentioned is moot as the entire page can easily be cached.Daniel
I wasn't disagreeing with you ;) just pointing out that HTML can be cached as well.Endotoxin
S
1

Classes are the re-usable styles that can be added to HTML elements. e.g-

<style> 
   .blue-text{color:Blue;}
</style>

you can use and re-use this blue-text class to any HTML element Note that in your CSS style element, classes should start with a period. In your HTML elements' class declarations, classes shouldn't start with a period. whereas inline style are like e.g-

<p style="color:Blue;">---</p>

So the difference between both is you can re-use classes whereas you can't re-use inline styles.

Simonnesimonpure answered 19/1, 2016 at 21:42 Comment(1)
In general you're right. But does this exact example make sense in production? I can re-use this inline style easily - just write style="color:Blue" - it takes me almost the same amount of code duplication as writing class="blue-text".Alcoholism
R
0

Inline Styles are definitely the way to go. Just look at http://www.csszengarden.com/ - that would never have been possible with classes and external style sheets...

or wait...

Rola answered 30/6, 2010 at 1:29 Comment(0)
A
0

Generally speaking, classes apply multiple styles. That's the main difference.

Most people say that classes are used for reusing the styles, and they feel pretty happy with classes that are simply aliases for single styles, for example, mb-100px, italic, color-red and etc. They think that color-red class is better than color:red style. Ok.

In my opinion, classes has nothing to do with reusage, but should be used to separate content from its appearance. That's it.

So, a class like color-red does not make any sense (unless you're using this class for a color palette element with red color).

A class should define element's purpose. Instead of multiple alias-classes mb-5 color-black flex text-center w-24 a single user-feedback-tile should be used.

Bad examples of classes usage is demonstrated in tailwindcss.com. What a "beautiful" (sarcasm) classes they suggest:

tailwindcss example

I especially "love" the class sm:w-[23.4375rem]. Ok, just kidding.

A class name should not assume an exact style. You should be able to change the appearance of HTML playing with the class styles only. If you have a class user-feedback-tile you can change its styles so that the same HTML looks totally different. But you cannot change style of classes like mb-5 or color-red for obvious reasons.

Check what MDN says about classes: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class#:%7E:text=Though%20the%20specification,the%20page%20changes:~:text=Though%20the%20specification,the%20page%20changes.

Though the specification doesn't put requirements on the name of classes, web developers are encouraged to use names that describe the semantic purpose of the element, rather than the presentation of the element. For example, attribute to describe an attribute rather than italics, although an element of this class may be presented by italics. Semantic names remain logical even if the presentation of the page changes.
Alcoholism answered 18/12, 2023 at 6:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.