Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 14, 2020 08:44 pm GMT

Responsive CSS Width

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.


Original Link: https://dev.to/ibn_abubakre/responsive-css-width-2jnm

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To