css揭秘
1、CSS编码技巧
- 尽量减少代码重复
在某些值相互依赖时,应把他们的相互关系用代码表示出来。
如:行高是字号的2倍,
font-size:20px(可使用百分比和em);line-height:2; - 代码易维护和代码量少不可兼得
如:
border-width:10px 10px 10px 5px,(代码量少); 如:border-width:10px; border-left-width:5px;(易维护); - 响应式网页设计
实现弹性可伸缩的布局,并在媒体查询的各个断点区间内指定相应尺寸。
如:
- 使用百分比取代固定宽度、长度;
- 当图片以行列式布局时,
display:inline-block或display:flex可以实现; - 为替换元素(浏览器根据元素的标签和属性决定元素具体显示内容,如img、video)设
max-width:100%;
2、用户体验
- 选用合适的鼠标光标
如:
- 表单提交后设置
cursor:not-allowed; - 视频播放器
cursor:none;
- 表单提交后设置
- 扩大可点击区域
border:10px solid transparent;background-clip:padding-box若还需设置border时不适用。此时可利用伪类position:absolute覆盖。 - 自定义复选框
- 1.隐藏原样式
position:absolute;clip:rect(0 0 0 0);rect demo 2.相邻label伪类覆盖原位置 ps : left >= right或者bottom <= top,则元素会被完全裁掉而不可见,即“隐藏”。通过这种方式隐藏的元素是可以被屏幕阅读器等辅助设备识别的.
- 1.隐藏原样式
3、结构与布局
- 自适应内部元素
width: min-content; - 垂直居中
- 1.父元素:
display:flex;align-items:center;justify-content:center; - 2.父元素:
display:flex;子元素:margin:auto; - 3.
padding: 100px calc(50% - 50px); - 4.视口居中
子元素
margin: 50vh auto 0;transform: translateY(-50%);
- 1.父元素:
- 根据数量设置样式
- 1.一个
li:only-child; - 2.n个 ```css li:first-child:nth-last-child(n), li:first-child:nth-last-child(n)~li{
}
- 3.小于n个 ```css li:first-child:nth-last-child(-a+n), li:first-child:nth-last-child(-a+n)~li{ }- 4.大于n个 ```css li:first-child:nth-last-child(a+n), li:first-child:nth-last-child(a+n)~li{
} ```
- 1.一个