Open In App

How to make a HTML div responsive using CSS ?

The CSS Media Query can be used to make an HTML “div” responsive. The media queries allow the users to change or customize the web pages for many devices like desktops, mobile phones, tablets, etc without changing the markups. Using the media query, the user can change the style of a particular element for different sizes of screen.

Note: The CSS @media rule consists of a media type and it can have one or more expressions, which can result in values like “true” or “false”.



The following meta viewport element has to be included in the “head” section of the HTML file for the responsive web page.

<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>



Syntax:

@media not|only mediatype and (expressions) {
// Your CSS codes
}

Approaches:

Example:




<!DOCTYPE html>
<html>
 
<head>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <style>
        * {
            font-size: 30px;
        }
 
        .mnb div {
            margin: 10px;
            height: 100px;
            width: 200px;
        }
 
        .first {
            width: 25%;
            display: inline-block;
            background-color: green;
        }
 
        .second {
            width: 25%;
            display: inline-block;
            background-color: blue;
        }
 
        .third {
            width: 25%;
            display: inline-block;
            background-color: yellow;
        }
 
        @media screen and (max-width: 500px) {
 
            .first,
            .second,
            .third {
                width: 70%;
            }
        }
    </style>
</head>
 
<body>
    <h1>Geeks for Geeks</h1>
    <p>Responsive div using css.</p>
    <div class="mnb">
        <div class="first">
            <p>First block</p>
        </div>
        <div class="second">
            <p>Second block</p>
        </div>
        <div class="third">
            <p>Third block </p>
        </div>
    </div>
    <p>
        The media query will only apply
        if the media type is screen
        and the viewport is equal to
        or less than 500px
    </p>
</body>
 
</html>

Output:be

Similarly, one can add or change various styles for a particular HTML element for different screen sizes by adding CSS code in @media query section as shown in the above example.


Article Tags :