简化媒体查询

53 阅读1分钟

sass 简化媒体查询

  • test.scss 文件
$breakpoint: (
	mobile: (
		0, 
		767px,
	),
	tablet: (
		768px, 
		1024px,
	),
	desktop: 1025px,
);

@mixin displayTo($breakname) {
	$bp: map-get($map: $breakpoint, $key: $breakname );

	@if type-of($bp)=='list' {
		$min: nth($bp, 1);
		$max: nth($bp, 2);
		@media screen and (min-width: $min) and (max-width: $max) {
			@content;
		}
	} @else {
		@media screen and (min-width: $bp) {
			@content;
		}
	}
}

@include displayTo('mobile') {
	.element {
		width: 200px;
		height: 789px;
	}
}

@include displayTo('tablet') {
	.element {
		width: 200px;
		height: 789px;
	}
}

@include displayTo('desktop') {
	.element {
		width: 200px;
		height: 789px;
	}
}
  • test.css(转化后的 css)
@media screen and (min-width: 0) and (max-width: 767px) {
  .element {
    width: 200px;
    height: 789px;
  }
}

@media screen and (min-width: 768px) and (max-width: 1024px) {
  .element {
    width: 200px;
    height: 789px;
  }
}

@media screen and (min-width: 1025px) {
  .element {
    width: 200px;
    height: 789px;
  }
}

less 简化媒体查询

@mobile: 0, 767px;
@tablet: 768px, 1024px;
@pc: 1025px;
.displayTo(@breakname, @style) {
    @value: @@breakname;

    & when not (ispixel(@value)) {
        @media screen and (min-width: extract(@value, 1)) and (max-width: extract(@value, 2)) {
            @style();
        }
    }
    & when (ispixel(@value)) {
        @media screen and (min-width: @value) {
            @style();
        }
    }
}

.displayTo(mobile, {
    background-color: red;
});
.displayTo(tablet, {
    background-color: yellow;
});
.displayTo(tablet, {
    background-color: yellow;
});