你可以看看其他常用的 CSS 技巧:
CSS 重置盒模型
*,
*::before,
*::after {
box-sizing: border-box;
}
当与将所有元素边距减为零的重置规则或父规则一起使用时,这会将上边距应用于其他元素后面的所有元素。这是一种快速获得垂直节奏的方法。
* + * {
margin-top: 1.5rem;
}
如果你真的想更具选择性,那么我喜欢在以下特定情况下将其作为后代使用:
article * + h2 {
margin-top: 4rem;
}
这类似于堆栈的思想,但更针对标题元素,以便在内容节之间提供更多的喘息空间。
清除浮动
- 使用
:after
伪元素并应用content: ''
以使其影响布局。 - 使用
clear: both
做出明确的元素都过去左右浮动。 - 将该元素设置为
display: block
块级元素才能正常运行
.clearfix::after {
content: '';
display: block;
clear:both;
}
注意:仅在用于
float
构建布局时,此选项才有用。考虑使用更现代的方法,例如flexbox
或grid
布局
:focus 状态样式
.input {
transition: 180ms box-shadow ease-in-out;
}
.input:focus {
box-shadow: 0 0 0 3px hsla(245, 100%, calc(82%), 0.8);
border-color: hsl(245, 100%, 42%);
outline: 3px solid transparent;
}
:focus-within
创建带有视觉,不可编辑前缀的输入。
- 当用户与
<input>
字段交互时,使用:focus-within
伪类选择器为父元素设置样式。
<div class="input-box">
<span class="prefix">+08</span>
<input type="tel" placeholder="888 8888" />
</div>
css 如下
.input-box {
display: flex;
align-items: center;
max-width: 300px;
background: #fff;
border: 1px solid #a0a0a0;
border-radius: 4px;
padding-left: 0.5rem;
overflow: hidden;
font-family: sans-serif;
}
.input-box .prefix {
font-weight: 300;
font-size: 14px;
color: #999;
}
.input-box input {
flex-grow: 1;
font-size: 14px;
background: #fff;
border: none;
outline: none;
padding: 0.5rem;
}
.input-box:focus-within {
border-color: plum;
}
实现分割线
实现分割线的方式有很多种,这里我们使用 flex
加伪元素(::before
和 ::after
)实现
.divider {
display: flex;
align-items: center;
}
.divider::before,
.divider::after {
content: '';
flex: 1;
height: 1px;
background: #dcdfe6;
}
.divider::before {
margin-right: 1rem;
}
.divider::after {
margin-left: 1rem;
}
另一种使用 grid
,左右两侧为水平线的标题可以构造为具有三列的网格:
.heading {
display: grid;
grid-template-columns: 1fr auto 1fr;
grid-gap: 1rem;
text-align: center;
}
1fr auto 1fr
表示左侧和右侧列的宽度相同,它们将占用剩余的空间。
我们可以使用 ::before
和 ::after
伪元素分别表示标题的左侧和右侧:
.heading::before,
.heading::after {
align-self: center;
border-top: 0.25rem double #e5e7eb;
content: '';
}
更多方法:CSS 巧妙实现分隔线的几种方法
CSS :empty
通常,我们希望为包含内容的元素设置样式。当元素完全没有子元素或文本时,该怎么办?您可以使用 :empty
选择器:
<p> </p>
<!-- 注意空白区 -->
<p></p>