BEM是一套针对css类样式的命名方法。(为了解决类名冲突)
其他命名方法还有:OOCSS、AMCSS、SMACSS等等
BEM全称是:Block Element Modifier
一个完整的BEM类名:blockelement_modifier,例如:`bannerdot_selected`,可以表示:轮播图中,处于选中状态的小圆点
三个部分的具体含义为:
- Block:页面中的大区域,表示最顶级的划分,例如:轮播图(
banner)、布局(layout)、文章(article)等等 - element:区域中的组成部分,例如:轮播图中的横幅图片(
banner__img)、轮播图中的容器(banner__container)、布局中的头部(layout__header)、文章中的标题(article_title) - modifier:可选。通常表示状态,例如:处于展开状态的布局左边栏(
layout__left_expand)、处于选中状态的轮播图小圆点(banner__dot_selected)
在某些大型工程中,如果使用BEM命名法,还可能会增加一个前缀,来表示类名的用途,常见的前缀有:
- l: layout,表示这个样式是用于布局的
- c: component,表示这个样式是一个组件,即一个功能区域
- u: util,表示这个样式是一个通用的、工具性质的样式,例如:u-color-primary{}
- j: javascript,表示这个样式没有实际意义,是专门提供给js获取元素使用的
实例:
轮播图页面:
index.html:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><link rel="stylesheet" href="./index.css"></head><body><div class="banner__container"><div class="banner__imgcontainer"><img src="https://img.alicdn.com/simba/img/TB1JqFeoH2pK1RjSZFsSuuNlXXa.jpg" alt=""><img src="https://img.alicdn.com/simba/img/TB1JqFeoH2pK1RjSZFsSuuNlXXa.jpg" alt=""><img src="https://img.alicdn.com/simba/img/TB1JqFeoH2pK1RjSZFsSuuNlXXa.jpg" alt=""></div><div class="banner__dotcontainer"> <!-- 圆点容器 --><span class="banner__dot banner__dot_selected"></span><span class="banner__dot"></span><span class="banner__dot"></span></div></div></body></html>
index.css:
.banner__container {
width: 520px;
height: 280px;
margin: 0 auto;
outline: 1px solid;
overflow: hidden;
position: relative;
}
.banner__imgcontainer {
width: 1560px;
height: 280px;
/* background: red; */
}
.banner__imgcontainer img {
float: left; /* 左浮动是指图片向左靠齐 */
width: 520px;
height: 280px;
}
.banner__dotcontainer {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
padding: 5px;
background: rgba(0, 0, 0, .5);
border-radius: 5px;
}
.banner__dot{
float: left;
width: 10px;
height: 10px;
background: #fff;
border-radius: 50%;
margin: 5px;
}
.banner__dot_selected{
background: #f40;
}
效果图:
