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" />
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. }
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.
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.
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”.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With