前言
有的時候寫項目,需要一些通用的css
樣式來實現一些功能,比如居中、漸變、單行溢出省略號、多行溢出省略號等.
項目使用的less
預處理器,所以整理了一些常見的mixin
函數
實現
新建mixin.less
文件,整理了一些筆者常用的幾個,其他的可以自行添加
具體less
如何使用可以看https://www.w3cschool.cn/less/less_installation.html
.ellipsis() {
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
}
//多行超出省略號
.ellipsisLine(@line : 2) {
word-break: break-all;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: @line;
overflow: hidden;
}
/*漸變(從上到下)*/
.linear-gradient(@direction:bottom, @color1:transparent, @color2:#306eff, @color3:transparent) {
//background: -webkit-linear-gradient($direction,$colorTop, $colorCenter, $colorBottom); /* Safari 5.1 - 6.0 */
background: -o-linear-gradient(@direction, @color1, @color2, @color3);
/* Opera 11.1 - 12.0 */
background: -moz-linear-gradient(@direction, @color1, @color2, @color3);
/* Firefox 3.6 - 15 */
background: linear-gradient(to @direction, @color1, @color2, @color3);
}
// 居中
.center(@width:null,@height:null) {
position: absolute;
top: 50%;
left: 50%;
& when (@width = null) and (@height= null){
transform: translate(-50%, -50%);
}
& when not(@width = null) and not(@height = null){
width: @width;
height: @height;
margin: -(@height / 2) 0 0 -(@width / 2);
}
& when not (@width = null) and (@height = null){
width: @width;
margin-left: -(@width / 2);
transform: translateY(-50%);
}
& when (@width = null) and not(@height=null){
height: @height;
margin-top: -(@height / 2);
transform: translateX(-50%);
}
}
使用
在項目頁面中
@import 'mixin.less'
.main {
height: 100vh;
width: 100vw;
h2 {
color: @primary-color;
font-size: @font-size-lg;
}
}
.class {
.center(100px, 100px);
.linear-gradient();
.ellipsis();
}
預編譯之後就變成
.main {
height: 100vh;
width: 100vw;
}
.main h2{
color: red;
font-size:16px;
}
.class {
position: absolute;
top: 50%;
left: 50%;
width: 2.66667rem;
height: 2.66667rem;
margin: -1.33333rem 0 0 -1.33333rem;
background: -webkit-linear-gradient(top, transparent, #306eff, transparent);
background: linear-gradient(to bottom, transparent, #306eff, transparent);
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
}
優化
如果多個頁面中都用到這個mixin.less
,我們需要在不同的less
文件下@import
這是個很累的過程,我們可以藉助萬能的webpack
去解決
筆者是基於vue-cli3
新建的項目,所以這裏以此環境表述
先安裝style-resources-loader
yarn add style-resources-loader
然後修改配置文件
// 全局注入theme.less
function addStyleResource (rule) {
rule.use('style-resource')
.loader('style-resources-loader')
.options({
patterns: [
path.resolve(__dirname, './src/assets/less/mixin.less'),
],
})
}
module.exports = {
chainWebpack(config) {
const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)))
}
}
注意配置文件中的那個文件地址就是我們需求全局引入的文件,記得修改之後重啓服務使配置生效
重啓完成之後,將每個頁面中的@import
刪除掉,刷新頁面,效果依然存在
關於
- 本文首發於自定義mixin.less並全局注入至項目中
- 參考文章:Vue-cli3-自動化導入