【问题标题】:Differential application of CSS styles to html elementsCSS 样式对 html 元素的不同应用
【发布时间】:2019-09-06 02:42:27
【问题描述】:

我想仅对手机和平板电脑等小屏幕应用 margin-top: 45px。以下是我的代码:

 @x-large: ~"only screen and (min-width: 1201px)";
 @large: ~"only screen and (max-width : 1200px)";
 @medium: ~"only screen and (max-width : 992px)";
 @small: ~"only screen and (max-width : 480px)";
 @x-small: ~"only screen and (max-width : 320px)";

 #myPanel {
  @media @small {
    margin-top: 45px !important;
  }

  @media @x-small {
    margin-top: 45px !important;
  }

  @media @tablet {
    margin-top: 45px !important;
  }

  @media @x-large {
    margin-top: 0px;
  }

  @media @large {
    margin-top: 0px;
  }
  }

问题是当我切换到桌面大小时,也会应用样式。我必须使用!important,否则它不适用于小屏幕。

【问题讨论】:

    标签: css


    【解决方案1】:

    我认为你只需要添加。

    @media @small {
      margin-top: 45px;
    }
    @media @x-large {
      margin-top: 0px;
    }
    

    【讨论】:

      【解决方案2】:

      我无法使用@media 查询使其工作。相反,我使用 jquery 解决了它。

      jQuery code:
          window.addEventListener("resize", resolvePanels);
          window.addEventListener("load", resolvePanels);
          function resolvePanels(e){
              var viewportWidth = $(window).width();
              if (viewportWidth < 1025) {
                  $("#myPanel").removeClass("noTopMargin").addClass("hasTopMargin");
              }
              else {
                  $("#myPanel").removeClass("hasTopMargin").addClass("noTopMargin");
              } 
          }
      
      CSS code
          .noTopMargin {
              margin-top: 0px;
          }
          .hasTopMargin {
              margin-top: 45px;
          }
      

      【讨论】:

      • 基本上,在窗口加载和调整大小事件期间,都会执行“resolvePanels(e)”函数。
      猜你喜欢
      • 2021-09-17
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 2011-02-05
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多