How to make the body width equal to the device-wid

2019-03-18 04:51发布

问题:

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" />

回答1:

Just use width: auto;

Difference between width: 100%; and width: auto; is that outer width for 100% is 100% + padding-left + padding-right, inner 100%. Outer width of width: auto is 100%, inner width is 100% - padding-left - padding-right if and only if display is block and no float is set (and no floated element without clear is before).



回答2:

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/