简体   繁体   English

使用CSS @media设置断点以响应屏幕尺寸

[英]Setting Breakpoints to respond to screen size using CSS @media

I'm setting breakpoints in css using '@media only screen and (max-width: 500px)'. 我使用'@media only screen and(max-width:500px)'在CSS中设置断点。

When I set it to change colour upon reaching the breakpoint it works: 当我将其设置为在达到断点时更改颜色时,它将起作用:

@media only screen and (max-width: 500px) {#container{color:black;}}

the container div does go black when I resize the browser, however when I set the breakpoint to change the margin of the div the breakpoint is not triggered. 调整浏览器大小时,容器div确实会变黑,但是当我设置断点以更改div的边距时,不会触发断点。

So when I set the query to: 因此,当我将查询设置为:

@media only screen and (max-width: 500px) {#container{margin-left: 0px;}}

nothing changes when the screen is resized in exactly the same way as when I resized when testing for colour change. 以与测试颜色变化时调整大小时完全相同的方式调整屏幕大小时,没有任何改变。

the main css file sets #container at margin-left; 主css文件在左边距设置#container; 18% and when this is changed manually to 0px it does shift the document all the way to the left of the viewport 18%,当手动将其更改为0px时,确实会将文档一直移到视口的左侧

I've tried various different styles and html elements but colour changes seem to be very reliable, they work in pretty much any combination, but resizing divs or repositioning does not seem to work at all. 我尝试了各种不同的样式和html元素,但是颜色更改似乎非常可靠,它们几乎可以任意组合使用,但是调整div的大小或重新定位似乎根本不起作用。 Why might this be? 为什么会这样呢?

Answer: 回答:

I was putting my @media query at the head of my css file , when I moved it to the foot of the css file it now resized. 我将@media查询放在css文件的开头,当我将它移到css文件的底部时,现在调整了大小。 It leaves the question though, why did it change the colour at the head of the file but not resize? 但这留下了一个问题,为什么它更改了文件开头的颜色却没有调整大小?

You can change margins just as reliably as you can background colours through media queries. 您可以像通过媒体查询来设置背景颜色一样可靠地更改边距。

See this for example: 例如:

http://jsfiddle.net/Q55MC/ http://jsfiddle.net/Q55MC/

#container {background: blue; margin: 50px; width: 200px; height: 200px;}

@media only screen and (max-width: 500px) {
    #container{background:black; margin: 0px;}
}

Try creating a demo so that people can have a better idea about what your trying to achieve. 尝试创建一个演示,以便人们可以更好地了解您要实现的目标。

It looks like the 18% style is taking precedence. 看起来18%的风格占了上风。

Try to override it with this: 尝试使用此方法覆盖它:

@media only screen and (max-width: 500px) {#container{margin-left: 0px !important;}} @media only屏幕和(最大宽度:500px){#container {margin-left:0px!important;}}

Would the @viewport meta declaration help? @viewport元声明会有所帮助吗?

Elegantly Resize Your Page With the @viewport CSS Declaration 使用@viewport CSS声明优雅地调整页面大小

be aware that this post uses @-viewport when it should just be @viewport 请注意,该帖子在应为@viewport时使用@-viewport @viewport

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM