Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the body width equal to the device-width automatically in CSS3 media query?

Tags:

I'm doing a mobile website now and trying to target different devices using CSS3 media queries. Part of my code is as follows:

@media screen and (max-width:320px) { body {     width: 320px; } /* some other style */   } 

As you can see, I have to set the body width explicitly to make sure it doesn't show the width I set for desktop in my normal css, which is 920px. I'm wondering if there is any way that the body width can be set automatically to the device width and I don't need to set this manually every time I create a new @media.

By the way, I also add the following code inside my head tag:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
like image 355
chaonextdoor Avatar asked Feb 26 '13 17:02

chaonextdoor


People also ask

How do you set a media query for a range of width?

Setting a particular "width-range" isn't any different from the way media queries are created. The only difference is the addition of more media feature expressions (that is, the screen width sizes). Take a look: @media only screen and (min-width: 360px) and (max-width: 768px) { // do something in this width range. }

How do I change the width of a device width in CSS?

The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device). The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.

How do you give a media query a minimum width and maximum width?

Combining media query expressions Max-width and min-width can be used together to target a specific range of screen sizes. @media only screen and (max-width: 600px) and (min-width: 400px) {...} The query above will trigger only for screens that are 600-400px wide.

What is device width media query?

The width media feature describes the width of the rendering surface of the output device (such as the width of the document window, or the width of the page box on a printer). And following is MDN's definition of “device-width”.


1 Answers

You can also use

width: 100vw; 

That will set the element to 100% of the viewport's width. You might want to check your browsers' compatibility before adding: http://caniuse.com/#search=vw

More info on viewport sizing: https://css-tricks.com/viewport-sized-typography/

like image 182
sh3nan1gans Avatar answered Oct 26 '22 14:10

sh3nan1gans