问题描述
在写CSS样式的时候,由于层次比较深,使用css嵌套的方式作用指定范围的样式是个不错的选择,直接用CSS写样式,会增加代码的复杂度,如果用sass就需要引入webpack或者后台编译器转换,如果工程比较小(只有一两个页面),使用webpack打包,就显得项目过于臃肿,因此,选择了less工具,在浏览器中可以直接访问
文章参考
less 介绍
CSS预处理器中Less的语法最接近原生CSS,学习成本比较低,语法比较简单,并且能够在浏览器客户端中预览,我这里只是简单的作为搭建less开发环境,可以在工作中熟练less相关的API和属性方法。
案例
静态页面,引入less和js文件
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet/less" type="text/css" href="less/list_icon.less">
<link rel="stylesheet" href="public/css/hb_wap.css">
<script src="public/js/less.js" type="text/javascript"></script>
<title>list icon 组件</title>
</head>
<body>
<div class="hb_list_container">
<div class="hb_item_container">
dsaf
</div>
<div class="hb_item_container">
dsaf
</div>
<div class="hb_item_container hb_icon_right">
dsaf
<span class="iconfont icon"></span>
</div>
<div class="hb_item_container hb_icon_left hb_icon_right">
<span class="iconfont icon"></span>
dsaf
<span class="iconfont icon"></span>
</div>
<div class="hb_item_container hb_icon_left">
dsaf
<span class="iconfont icon"></span>
</div>
</div>
</body>
</html>
less文件内容(语法)
@border_color:#eee;
@item_height:45px;
@item_padding_width:60px;
.hb_list_container{
display: block;
.hb_item_container{
border-bottom: 1px solid @border_color;
height: @item_height;
line-height: @item_height;
position: relative;
&.hb_icon_right{
padding-right: @item_padding_width;
.iconfont:first-child{
position: absolute;
top: 0px;
right: 0px;
line-height: @item_height;
}
}
&.hb_icon_left{
padding-left: @item_padding_width;
.iconfont:last-child{
position: absolute;
top: 0px;
left: 0px;
line-height: @item_height;
}
}
}
}
案例说明
- 引用less文件的方式
<link rel="stylesheet/less" type="text/css" href="less/list_icon.less">
- 引用对less解析的js函数
<script src="public/js/less.js" type="text/javascript"></script>
一定要以less文件的方式写less代码
引入less.js文件,需要在引入less文件后面,否则无法起到作用