Syntax error Changing Column Width Based on Screen Size using CSS

Changing Column Width Based on Screen Size using CSS



To change the column width based on screen size, use media queries. Media Queries is used when you need to set a style to different devices such as tablet, mobile, desktop, etc.

First, set the div −

<div class="sample">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quod, maiores!</div>

Set the Initial Width

To set the width of the above div, use the width property in CSS −

.sample {
   width: 50%;
   background-color: lightblue;
   height: 200px;
   font-size: 18px;
}

Change the Column Width

Now, to change column width on the basis of screen size, set the width to 100% −

.sample {
   width: 100%;
}

When the screen size gets smaller than 700px, the width is 100% −

@media only screen and (max-width: 700px) {
   body {
      margin: 0;
      padding: 0;
   }
   .sample {
      width: 100%;
   }
}

Example

The following is the code to change the column width based on screen size −

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      .sample {
         width: 50%;
         background-color: lightblue;
         height: 200px;
         font-size: 18px;
      }
      @media only screen and (max-width: 700px) {
         body {
            margin: 0;
            padding: 0;
         }
         .sample {
            width: 100%;
         }
      }
   </style>
</head>
<body>
   <h1>Changing column width based on screen size</h1>
   <div class="sample">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quod, maiores!</div>
   <p>Resize the browser window to 700px and below to see the above div width change to 100%</p>
</body>
</html>
Updated on: 2023-10-30T14:41:32+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements