在30秒内可以被读懂的实用CSS代码片段合集
Clearfix 清除浮动
确保元素自行清除其子元素。
注意:这只在你仍然使用float来构建布局时才有用。 请考虑使用灵活布局或网格布局的现代方法。
HTML
<div class="clearfix">
<div class="floated">float a</div>
<div class="floated">float b</div>
<div class="floated">float c</div>
</div>
CSS
.clearfix::after {
content : "" ;
display : block ;
clear : both ;
}
.floated {
float : left ;
}
原型
float a
float b
float c
解释
1. .clearfix::after 定义了一个伪元素
2. content: '' 允许伪元素影响布局
3. clear: both 指示元素的左侧,右侧或两侧不能与相同块格式化上下文中较之前的浮动元素相邻。
浏览器支持
99+%
✅无注意事项
宽高比恒定
给定可变宽度的元素,它将确保其高度以响应方式保持一定的比例(即其宽高比保持不变)。
HTML
<div class="constant-width-to-height-ratio"></div>
CSS
.constant-width-to-height-ratio {
background : #333 ;
width : 50% ;
padding-top : 50% ;
}
原型
调整浏览器窗口的大小以查看元素的比例保持不变。
(附图)
解释
padding-top
和padding-bottom
可以用作height
的替代,这样百分比值可以使元素的高度变成其父宽度的百分比,即50%表示高度将是父元素宽度的50%, 意味着它的行为与width
相同。 这使得其比例保持不变。
浏览器支持
99+%
⚠️ padding-top 将元素内的任何内容推到底部。
自定义文本选择
更改文本选择的样式
HTML
<p class="custom-text-selection">Select some of this text. </p>
CSS
.custom-text-selection::selection {原型
background : red ;
color : white ;
}
Select some of this text.
解释
::selection
在元素上定义一个伪选择器,以便在选中时对其中的文本进行样式设置
浏览器支持
84.6+%
⚠️ 需要前缀才能获得全面支持,实际上并不符合任何规范。