媒体查询 & less

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2022-07-07

使用range和each实现一个循环,需要Less v3.9.0

each(range(4), {
  .col-@{value} {
    width: (@value * 50px);
  }
})

// 等同于

.col-1 {
  width: 50px;
}

.col-2 {
  width: 50px;
}

.col-3 {
  width: 50px;
}

.col-4 {
  width: 50px;
}

变量设置

// variables.less
@css-prefix:  '';

@minimum-screen: 320px;
@mobile:768px;
@ipad: @mobile+1px;
@medium-screen: 992px;
@desktop: 1200px;
@wide-screen: 1920px;
@column-gap:15px;
@content-max-width:1200px;
@font-base: 192;

html {
  font-size: @font-base * 1px;
}

@media screen and (max-width: @minimum-screen) {
  html {
    font-size: @font-base * 1px;
  }
}

@media screen and (min-width: @minimum-screen) and(max-width: @mobile) {
  html {
    font-size: @font-base * 1px;
  }
}

@media screen and (min-width: @wide-screen) {
  html {
    font-size: 10vw;
    font-size: @font-base * 1px;
  }
}

/* html
screen <= 320         font-size:17.06667px
320 < screen < 540    font-size: 20px; 5.33333vw;
screen >= 540         font-size: 28.5px;
screen >= 1080        font-size: 57.6px;
*/

body {
  font-size: 16px;
}

@px2rem: @font-base * 1rem;
@px2mobilerem: 75 * 1rem;

.px2mobile(@key, @px) {
  @{key}: unit(@px / 75, rem);
}

.rem(@key, @px) {
  @{key}: unit(@px / @font-base, rem);
}

栅格设置

// grid.less
@import 'variable.less';

// 栅格系统 12栅格,非响应式
each(range(12),{
  .col-@{value}{
    width: (100/12 * 1% * @value);
  }
});

// 移动端按整行显示 <= 768px
@media screen and (max-width: @mobile) {
  each(range(12),{
    .col-xs-@{value}{
      width: 100%;
    }
  });

  .hidden-xs {
    display: none !important;
  }
}

// ipad桌面 > 768px && <= 992px
@media screen and (min-width: @mobile + 1px) and (max-width: @medium-screen) {
  each(range(12),{
    .col-sm-@{value}{
      width: (100/12 * 1% * @value);
    }
  });

  .hidden-sm {
    display: none !important;
  }
}

// 小型桌面 > 992px && <= 1200px
@media screen and (min-width: (@medium-screen + 1px)) and (max-width: @desktop) {
  each(range(12),{
    .col-md-@{value}{
      width: (100/12 * 1% * @value);
    }
  });

  .hidden-md {
    display: none !important;
  }
}

// 一般桌面 + 大屏 > 1200px
@media screen and (min-width: (@desktop + 1px)) {
  each(range(12),{
    .col-lg-@{value}{
      width: (100/12 * 1% * @value);
    }
  });

  .hidden-lg {
    display: none;
  }
}

[class*=col-] {
  box-sizing: border-box;
  padding: @column-gap;
  .is-mobile({
    .px2mobile(padding, @column-gap);
  });
}

// <= 768px
.is-mobile(@rules) {
  @media screen and (max-width: @mobile) {
    @rules();
  }
}
// > 768px && <= 992px
.is-ipad(@rules) {
  @media screen  and (min-width: (@mobile + 1px)) and (max-width: @medium-screen) {
    @rules();
  }
}
// > 992px && <= 1200px
.is-desktop(@rules) {
  @media screen and (min-width: (@medium-screen + 1px)) and (max-width: @desktop) {
    @rules();
  }
}
// > 1200px
.is-widescreen(@rules) {
  @media screen and (min-width: @desktop + 1px) {
    @rules();
  }
}