jadle
jadle

Reputation: 147

How to avoid inline css in dynamic wordpress style?

I'm developing a Wordpress theme that allows a client to upload their own header background image. But I don't want the image to load for mobile users. Here is what's working for me right now:

<div class="header" style="
    @media (min-width: 676px) { 
        background-image: linear-gradient(to right, rgba(1, 1, 1, 0.7), rgba(1, 1, 1, 0.1) 35%), 
        url('<?php header_image(); ?>'); 
    }
">

This works, but it's a lot of inline styling. Is there a way to avoid having so much inline css? Here's another method I tried that DIDN'T work:

function header_image_style() {

    $header_image = header_image();

    return "<style type='text/css'>
                .header{
                    background-image: 
                    linear-gradient(to right, rgba(1, 1, 1, 0.7), rgba(1, 1, 1, 0.1) 35%), 
                    url('".$header_image."');
                }
            </style>";
}

This method only outputs the $header_image url to the page when header_image_style(); is called, and ignores all the other css. What is the best-practice method to achieve what I'm doing?

Upvotes: 0

Views: 1243

Answers (2)

Dreamm
Dreamm

Reputation: 141

check this function wp_is_mobile detecting over 95% devices. Have good experience with it. As for me works fine

Upvotes: 1

johnnyd23
johnnyd23

Reputation: 1705

At the very least you could clean up your inline styling by moving the media query to your external CSS file, and using a max-width query instead to disable the background image

@media (max-width: 675px) { 
    .header {
        background-image: none!important; 
    }
}

Upvotes: 0

Related Questions