5

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 I agree that this is the use case for inline CSS properties.
Indeed. It's a shame that people get so crazy about saying "never use inline CSS" that people never do, even when it's the right tool. And of course, you can abstract that philosophy to just about any technology :)
I try to use classes as much as possible for "variable" css. Something like <p class="{{ model.some_field }}"> which works in some specific cases, like integers in known ranges, limited foreignkeys, etc. But looking at your case, I think I might actually integrate that into my project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.