Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSS技巧:使用REM减少代码重复之button #7

Open
GreyGao opened this issue Jul 16, 2017 · 0 comments
Open

CSS技巧:使用REM减少代码重复之button #7

GreyGao opened this issue Jul 16, 2017 · 0 comments

Comments

@GreyGao
Copy link
Owner

GreyGao commented Jul 16, 2017

在写CSS的过程中,尽量减少代码的重复,对于代码阅读和维护的好处是显而易见的。在修改代码时,需要改动的变量越少,意味着可能出错的地方就越少,花费时间也越少。
在开始写一个页面的CSS时,尝试去思考如何从更简约的角度去定义一些root型的CSS规范,减少代码冗余,提升质量。

比例优化

以下是一个案例,为按钮添加一些CSS效果:

.button1 {
  padding: 0.375rem 1rem;
  border: 1px solid #446d88;
  background: #58a linear-gradient(#77a0bb, #58a);
  border-radius: 0.25rem;
  box-shadow: 0 1px 5px gray;
  color: white;
  text-shadow: 0 -1px 1px #335166;
  font-size: 1.25rem;
  line-height: 1.5;
}

得到的按钮效果如下:

image图1

在这段CSS中,如果我们需要修改按钮的字体大小的话,我们同时还需要修改按钮的行高,同时因为字体很大的话,我们的圆角效果也会变得不协调,因为我们的效果都是为小按钮设计的。
由于我们在移动端经常需要使用REM来进行等比例大小缩放设计,所以为类似按钮这些元素做好基本的CSS设计就显得至关重要。
下面是优化后的button1

//为HTML设置默认字体大小为原来2倍
html{font-size:32px;}       
        
.button2 {
  //将padding的尺寸修改为相对于htm页面的rem
  padding: 0.375rem 1rem;
  border: 1px solid rgba(0, 0, 0, .1);
  background: #000 linear-gradient(hsla(0, 0%, 100%, .2), transparent);
  //border的圆角也会根据按钮的大小同比调整
  border-radius: 0.25rem;
  box-shadow: 0 0.05rem .25rem rgba(0, 0, 0, .5);
  color: white;
  text-shadow: 0 -0.05rem .05rem rgba(0, 0, 0, .5);
  //字体相对于页面大小为1.25倍
  font-size: 1.25rem;
  //行高是字体的1.5倍
  line-height: 1.5;
}

得到的结果则是一个同比放大2倍的button1

image图2

以后只需要修改rem的root font-size即可等比例自动调整按钮的大小。当然有些时候我们并不希望全部页面都被一个定义尺寸牵制,也可以适当的使用em来替换。

颜色优化

除了比例以外,不同功能用途的按钮颜色也会不同,如何快速设置不同用途按钮的渐变色,我们可以做以下设置。

.button2 {
  padding: 0.375rem 1rem;
  border: 1px solid rgba(0, 0, 0, .1);
  //为按钮的主色调增加一层白色或黑色的透明遮罩
  background: #000 linear-gradient(hsla(0, 0%, 100%, .2), transparent);
  border-radius: 0.25rem;
  box-shadow: 0 0.05rem .25rem rgba(0,0,0,.5);
  color: white;
  text-shadow: 0 -0.05rem .05rem rgba(0, 0, 0, .5);
  font-size: 1.25rem;
  line-height: 1.5;
}

这样我们只要再修改background-color属性,就可以生成不同属性的按钮了。

#cancel {
  background-color: #c00;
}
#ok {
  background-color: #6b0;
}

得到效果如下图:

image 图1-3

总结

通过这种方式我们就可以快速定制大部分的需求按钮。简洁而易维护,不重复的代码不仅是审美上的需求,更是实际工作中协同工作的重要需求,每次完成一个页面时,我会重新浏览一下之前写过的CSS和JS,即便现在的水平无法优化到最简洁,也应该在注释或者笔记里标注下冗余的部分,在以后的学习中去跨越这些障碍。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant