CSS媒体查询和!重要

时间:2012-04-21 19:07:34

标签: css media-queries

我有一个使用@media查询的网站,但它似乎没有设置它们。它们始终保持默认样式。

例如:

#div1 { background:red}

@media screen and (max-height:912px) {
#div1{background:blue}
}
除非我使用!important,否则

将始终坚持背景:红色,但在我的媒体查询中,我正在为这么多选择器设置样式。我是否需要设置每个选择器样式!important

6 个答案:

答案 0 :(得分:8)

我遇到了同样的问题。我意识到媒体查询必须在样式表的末尾(即使您在工作流程中使用/导入多个文件)。

答案 1 :(得分:3)

将最大高度更改为最小高度:http://jsfiddle.net/jnQYb/

答案 2 :(得分:2)

它适用于我。

看一下:http://jsfiddle.net/TUL6h/1/ - 背景为红色,但是当您更改结果部分高度时,它会在某个点上变为蓝色。

您正在尝试使用哪种浏览器?

答案 3 :(得分:0)

不一定,!important 用于覆盖默认css,即覆盖默认样式中使用的属性。因此,如果媒体查询中有新属性,则不必将其与其一起使用。

答案 4 :(得分:0)

在@media查询中包含的!important内部使用!important是向页面元素添加动态样式属性的有效方法,同时保留“默认”css以便于维护。

示例:

<html>
    <head>
    <style>
    @media all and (max-width: 768px) {

    /* CSS styles targeting screens of smaller sizes and/or resolutions (IE phones and tablets)  */

        #semantically-named-element p 
        { width: 60% !important;
        background: rgba(0,0,255,1)!important;
        margin: auto !important; }

        #semantically-named-element span 
        { display: none !important; }

    } 
    /* Look ma no media queries needed for default CSS below! Very easy to discern default styles, when the default code is the stuff not wrapped in queries. Period. */    

    /* Default CSS style attributes for any viewports that do not fit into the low or high resolution/screen size parameters set above and below. Also the fallback for browsers that still disregard CSS media queries */  
    #semantically-named-element p 
        { width: 90%;
          background: rgba(255,0,0,1);
          margin: auto; }

    #semantically-named-element span 
        { display: block;
          background: rgba(0,0,0,0.8);
          color: #FFF;
          text-align: center;}  
    @media all and (min-width: 968px) {
    /* CSS styles targeting very large or very high resolution viewports at the 769 pixels wide "break-point" */
        #semantically-named-element p 
        { width: 80% !important;
        background: rgba(0,255,0,1)!important;
        margin: auto !important; }

        #semantically-named-element span 
        { display: block !important;
        background: rgba(0,0,0,0.8)!important;
        color: #FFF !important; font-size: 200%; }
    }
    </style>
  </head>

  <body>
      <div id="semantically-named-element">  
        <p> Usage of !important inside of the code contained within your @media queries is an effective way to add dynamic style properties to your pages elements, while leaving your 'default' css intact for easy maintenance.<span>hidden until tablet greater 768 viewport pixel width</span></p>
      </div>  
   </body>
</html>

答案 5 :(得分:0)

在//jsfiddle.net/TUL6h/55/中查看您的示例: 您需要更改媒体查询的顺序。     最大高度:510px; 包括     最大高度:500像素; 它必须首先才能显示更特殊的500px beeing情况。