重置组件和共用样式

1,524 阅读2分钟

前言:

开发时修改默认样式是很麻烦的一件事,这时我们可以用重置样式的包来解决这一麻烦

介绍normalize.css

Normalize.css 是一个很小的CSS文件,但它在默认的HTML元素样式上提供了跨浏览器的高度一致性。是一种现代的、为HTML5准备的优质替代方案。

特点:

  • 保护有用的浏览器默认样式 而不是完全去掉它们
  • 一般化的样式:为大部分HTML元素提供
  • 修复浏览器自身的bug 并保证各浏览器的一致性
  • 优化CSS可用性:用一些小技巧
  • 解释代码:用注释和详细的文档来 Normalize.css支持包括手机浏览器在内的超多浏览器,同时对HTML5元素、排版、列表、嵌入的内容、表单和表格都进行了一般化。尽管这个项目基于一般化的原则,但我们还是在合适的地方使用了更实用的默认值。

任务目标:

引入normalize.css源码并在此基础上构建,必要的时候用你自己写的CSS覆盖默认值。

具体步骤:

1)下载导入

执行 npm i normalize.css 安装重置样式的包,然后在 main.js 导入 normalize.css 即可

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
+import 'normalize.css'

createApp(App).use(store).use(router).mount('#app')

2) 引入样式

新建文件 src/styles/common.less 在该文件写入常用的样式,然后在 main.js 导入即可

src/styles/common.less

// 重置样式
* {
  box-sizing: border-box;
 }
 
 html {
   height: 100%;
   font-size: 14px;
 }
 body {
   height: 100%;
   color: #333;
   min-width: 1240px;
   font: 1em/1.4 'Microsoft Yahei', 'PingFang SC', 'Avenir', 'Segoe UI', 'Hiragino Sans GB', 'STHeiti', 'Microsoft Sans Serif', 'WenQuanYi Micro Hei', sans-serif
 }
 
 ul,
 h1,
 h3,
 h4,
 p,
 dl,
 dd {
   padding: 0;
   margin: 0;
 }
 a {
   text-decoration: none;
   color: #333;
   outline: none;
 }
 i {
   font-style: normal;
 }
 input[type="text"],
 input[type="search"],
 input[type="password"], 
 input[type="checkbox"]{
   padding: 0;
   outline: none;
   border: none;
   -webkit-appearance: none;
   &::placeholder{
     color: #ccc;
   }
 }
 img {
   max-width: 100%;
   max-height: 100%;
   vertical-align: middle;
   background: #ebebeb url(../assets/images/200.png) no-repeat center / contain;
 }
 ul {
   list-style: none;
 }
 #app {
   background: #f5f5f5;
   user-select: none;
 }
 
 .container {
   width: 1240px;
   margin: 0 auto;
   position: relative;
 }
 .ellipsis {
   white-space: nowrap;
   text-overflow: ellipsis;
   overflow: hidden;
 }
 
 .ellipsis-2 {
   word-break: break-all;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   overflow: hidden;
 }
 
 .fl {
   float: left;
 }
 
 .fr {
   float: right;
 }
 
 .clearfix:after {
   content: ".";
   display: block;
   visibility: hidden;
   height: 0;
   line-height: 0;
   clear: both;
 }

src/main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'import 'normalize.css'
+import '@/styles/common.less'createApp(App).use(store).use(router).mount('#app')

总结:

  1. 重置样式,屏蔽浏览器之间的差异
  2. 添加全局通用样式文件