Responsive CSS styles inline on the fly

I am currently working on a highly design orientated site based on wordpress CMS.

Currently I have a responsive main stylesheet linked externally for the core css. As the site relies heavily on spacing and alignments of both text and images it has become necessary to add inline css using style= HTML to sometimes override the external CSS.

Read More

The problem I have is that in most cases certain elements such as margins need to be a different percentage in the mobile view than the desktop view to balance the visual composition. Is there any way to add responsiveness to the inline CSS based on screen width as can be done in an external style sheet?

So far the only way I can think of achieving this is through jQuery amending the external CSS based on the users screen width however this would mean setting up strict rules in the JS eg: for desktop view having margins set at 70% and for mobile setting them to 90%.

If it could be possible to do this inline using html style then this would give my client stricter control and more flexibility. Luckily my client is well versed in CSS.

Related posts

Leave a Reply

3 comments

  1. You could always add a block of css inline with a style element:

    <style type="text/css">
    @media screen and (min-width:800px) {
       .inlineOverride {
         /* add more styles here */
       }       
    }    
    </style>
    
    <div class="inlineOverride">
    </div>
    

    It’s worth mentioning that HTML5 has introduced a scoped attribute that you can set on the style element to limit the specified style information to the style element’s parent element, and that element’s descendants.

    It isn’t widely supported yet, so shouldn’t be relied on, but it could be useful in the long term to help prevent inline styles like this from “leaking” into other parts of the document.

  2. In modern Browsers you can (kind of) archive this by using custom css properties (css variables):

    @media (max-width: 1100px) {
      * {
        color: var(--color-sm)
      }
    }
    <a style="--color-sm: #11f">Text</a>

    (Expand Snippet or open in full page to get the other behavior)

    (Color is used for simplicity of presentation, just use margin or any other css property according to your use case.)