大家好,今天在浏览 css-tricks.com 这个网站时,看到一个浮动节标题的列表案例,就是简简单单的用 CSS + HTML 实现了一个我们会经常遇到通讯录列表需求(按字母吸附滑动列表),以前实现老麻烦了,看到这个案例,我就迫不及待的想分享给大家,废话不多说,赶紧看看是怎么实现的。
<div class="floating-stack">
<dl>
<dt>A</dt>
<dd>Algeria</dd>
<dd>Angola</dd>
<dt>B</dt>
<dd>Benin</dd>
<dd>Botswana</dd>
<dd>Burkina Faso</dd>
<dd>Burundi</dd>
<dt>C</dt>
<dd>Cabo Verde</dd>
<dd>Cameroon</dd>
<dd>Central African Republic</dd>
<dd>Chad</dd>
<dd>Comoros</dd>
<dd>Congo, Democratic Republic of the</dd>
<dd>Congo, Republic of the</dd>
<dd>Cote d'Ivoire</dd>
<dt>D</dt>
<dd>Djibouti</dd>
<dt>E</dt>
<dd>Egypt</dd>
<dd>Equatorial Guinea</dd>
<dd>Eritrea</dd>
<dd>Eswatini (formerly Swaziland)</dd>
<dd>Ethiopia</dd>
</dl>
</div>
完成后,在浏览器默认的效果如下:
从上图的效果可以看出,<dt>
标签在相对 <dd>
标签的左侧,<dt>标签主要是用于定义一个描述列表的项目/名字(可以理解为目录里的章)。<dd>标签被用来对一个描述列表中的项目/名字进行描述(可以理解目录里的节)。<dd>标签与<dl> 和 <dt>一起使用。
接下来,我们来看看最神奇的CSS部分,主要靠 CSS 实现按节固定滑动,示例代码如下:
dt {
position: sticky;
top: 0;
background: white;
display: inline-block;
}
完成后的效果如下视频所示:
好了,到这里我们的代码部分就完成了,很轻松完成了这个案例,是不是很简单呢。
你也许会认为这么丑的列表怎么拿的出手,那么我们来美化下列表,完善后的 HTML 和 CSS 部分如下:
<div class="container">
<div class="floating-stack">
<dl>
<dt>A</dt>
<dd>Algeria</dd>
<dd>Angola</dd>
<dt>B</dt>
<dd>Benin</dd>
<dd>Botswana</dd>
<dd>Burkina Faso</dd>
<dd>Burundi</dd>
<dt>C</dt>
<dd>Cabo Verde</dd>
<dd>Cameroon</dd>
<dd>Central African Republic</dd>
<dd>Chad</dd>
<dd>Comoros</dd>
<dd>Congo, Democratic Republic of the</dd>
<dd>Congo, Republic of the</dd>
<dd>Cote d'Ivoire</dd>
<dt>D</dt>
<dd>Djibouti</dd>
<dt>E</dt>
<dd>Egypt</dd>
<dd>Equatorial Guinea</dd>
<dd>Eritrea</dd>
<dd>Eswatini (formerly Swaziland)</dd>
<dd>Ethiopia</dd>
</dl>
</div>
</div>
.floating-stack {
background: #455a64;
color: #fff;
height: 300px;
width: 320px;
border-radius: 1rem;
overflow-y: auto;
}
.floating-stack > dl {
margin: 0 0 1rem;
display: grid;
grid-template-columns: 2.5rem 1fr;
align-items: center;
}
.floating-stack dt {
position: sticky;
top: 0.5rem;
left: 0.5rem;
font-weight: bold;
background: #263238;
color: #cfd8dc;
height: 2rem;
width: 2rem;
border-radius: 50%;
padding: 0.25rem 1rem;
grid-column: 1;
display: inline-flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
}
.floating-stack dd {
grid-column: 2;
margin: 0;
padding: 0.75rem;
}
.floating-stack > dl:first-of-type > dd:first-of-type {
margin-top: 0.25rem;
}
body {
background: #0d0d16;
color: white;
height: 100vh;
margin: 0;
display: grid;
place-items: center;
font: 100%/1.4 system-ui;
}
3.3、完成后的效果
好了,到这里我们的案例就完成了,是不是看起来很专业呢,大家可以点击阅读阅文看下(链接:https://www.30secondsofcode.org/css/s/sticky-list-titles),今天的文章就分享到这里,感谢你的阅读。
参考链接:https://css-tricks.com/sticky-definition-lists/ 作者:Chris Coyier