loading...
Cover image for Responsive CSS Width

Responsive CSS Width

ibn_abubakre profile image Abdulqudus Abubakre ・2 min read

Have you been writing CSS and you had to use media queries just so your website could look good across all devices? Well, the good news is, you don't always need media queries.
This series would be focused on various CSS tricks you could use to make your site responsive without using so much media queries.

In this article, we would be looking at how you can make the width of a particular element resize automatically without having to write several media queries.

Here's how you can go about it:

.container {
  width: 1200px;
  max-width: 100%;
}

Basically, we're saying the container element should have a width of 1200px but at no point should it exceed the maximum width of the parent which is 100%. So if the parent has a width greater than 1200px, the element would grow to 1200px, but if the parent is less than 1200px, the element would only take up 100%.

Let's use this knowledge to create a container class that will house the content of our application.

.container {
  width: 1200px;
  max-width: calc(100% - 20px);
  margin: 0 auto;
  padding: 0 10px;
}

In this case, we added a margin of 0 auto which would center the element horizontally on the page, and also a padding of 0 10px which would add spacing within the element on the left and right side. You might have noticed the change in our max-width property. We're doing this to account for the padding we added to the element. The calc(100% - 20px) is telling CSS to subtract 20px from the 100% and setting it as the max-width. Without this property, the total width of the element when the parent is less than 1200px would become 100% + 10px padding on the left + 10px padding on the right.

With this, we have a container that looks good on small devices and does not exceed a 1200px no matter how large the screen size which is good.

Here's a codepen link showing how it would in code.

Posted on by:

ibn_abubakre profile

Abdulqudus Abubakre

@ibn_abubakre

Front end developer, JavaScript enthusiast, Community Builder

Discussion

markdown guide
 

Great I came across a project today and it didn't have a single media query bt the responsive was still showing for mobile devices.... Nice post bro

 

I highly recommend adding css clamp to this post and if you want to exceed the beginners conventions, you have to cover css units (em, rem, ch,...)

 

This is helpful. Thank you Abdulqudus