CSS 如何在CSS3媒体查询中自动使主体宽度等于设备宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15095833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make the body width equal to the device-width automatically in CSS3 media query?
提问by chaonextdoor
I'm doing a mobile website now and trying to target different devices using CSS3 media queries. Part of my code is as follows:
我现在正在做一个移动网站,并尝试使用 CSS3 媒体查询来定位不同的设备。我的部分代码如下:
@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
.
如您所见,我必须明确设置主体宽度以确保它不会显示我在普通 css 中为桌面设置的宽度,即 920px。我想知道是否有任何方法可以将主体宽度自动设置为设备宽度,并且每次创建新的@media
.
By the way, I also add the following code inside my head
tag:
顺便说一下,我还在我的head
标签中添加了以下代码:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
回答by sh3nan1gans
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
这会将元素设置为视口宽度的 100%。您可能需要在添加之前检查浏览器的兼容性:http: //caniuse.com/#search=vw
More info on viewport sizing: https://css-tricks.com/viewport-sized-typography/
有关视口大小的更多信息:https: //css-tricks.com/viewport-sized-typography/
回答by Boris ?u?ka
Just use width: auto;
只需使用 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).
width: 100%;
和之间的区别在于width: auto;
100% 的外部宽度是100% + padding-left + padding-right
,内部100%
。width: auto
is 的外部宽度100%
,内部宽度是100% - padding-left - padding-right
当且仅当display
isblock
和 nofloat
被设置(并且之前没有没有 clear 的浮动元素)。