Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is inline CSS in Django avoidable?

I've heard recommendations saying that you should not use inline CSS, like:

<div style="min-width: 10em;">...</div>

but that you should use class instead, separating the CSS from the HTML, and (if possible) putting them in a separate CSS file.

So far, so good; it all makes sense -- at least as long as things fit into your model.

Now I run into Django, and I want to say something like:

{% for a, b in bar %}
    <div style="min-width: {% widthratio a b 100 %}em;">...</div>
{% endfor %}

Is there a practical way to avoid inline CSS here? Or do I just have to break The Norm?

like image 543
user541686 Avatar asked Jul 19 '11 20:07

user541686


People also ask

Should inline CSS be avoided?

Inline styles, while they have a purpose, generally are not the best way to maintain your website. They go against every one of the best practices: Inline styles don't separate content from design: Inline styles are exactly the same as embedded font and other clunky design tags that modern developers rail against.

Why is inline CSS a bad idea?

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.

Is inline CSS OK?

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.


1 Answers

Since it's a calculated value, you would use inline CSS. Inline CSS is there for a reason: CSS that isn't reusable across multiple elements/pages/websites.

Since you can't calculate from a CSS file, clearly it makes sense to use inline CSS here.

P.S. I am doing almost the exact same thing in a Django template, except mine is to center an image vertically and horizontally, and I have to use the image's actual proportions to calculate the centering CSS, so I can't use a class either.

like image 73
Jordan Avatar answered Oct 27 '22 10:10

Jordan