Search code examples
cssmedia-queries

Use CSS media query within an existing CSS class


I have an existing CSS class which used for all devices and I would love to add a media field which will override an existing one in order to be applied to some small phone screens.

Can you give an example of how do we use this.

Best


Solution

  • You need media queries for that. Add your styles within this block

    @media only screen and (max-device-width:480px){
        /* styles for mobile browsers smaller than 480px; (iPhone) */
    }
    

    Similarly you can also media queries within following block.

    @media only screen and (device-width:768px){
        /* default iPad screens */
    }
    
    /* different techniques for iPad screening */
    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
        /* For portrait layouts only */
    }
    
    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
        /* For landscape layouts only */
    }
    

    EXAMPLE

    Let us say you have following styles

    .color-me {
        color : red;
    }
    
    @media only screen and (max-device-width:480px){
        .color-me {
            color : blue;
        }
    }
    

    And this is your markup

    <div class="color-me">Color me</div>
    

    Now, the color of text will be red everywhere except for devices with width less than equal to 480px.