在看CSS选择符的时候注意到一个特别有意思的选择符–:target,随后在http://benschwarz.github.io/gallery-css/发现利用该选择符可以做出如此漂亮的gallery,干净利落无需js代码(强迫症及完美主义必备),网站上有一套讲解教程,但是是付费的。今天把我实现的过程以及某些细节分享出来,供学习使用。
在开始之前强烈建议先看一下css选择器拾遗
我这里有一个在线预览点击这里
如果对你有帮助的话就给一颗星吧github代码
html模板
<div class="gallery">
<div id="gallery-1" class="control-operator"></div>
<div id="gallery-2" class="control-operator"></div>
<div id="gallery-3" class="control-operator"></div>
<figure class="item">
<img src="./slide1.jpg" />
</figure>
<figure class="item">
<img src="./slide2.jpg" />
</figure>
<figure class="item">
<img src="slide3.jpg" />
</figure>
<div class="controls">
<a href="#gallery-1" class="control-button">•</a>
<a href="#gallery-2" class="control-button">•</a>
<a href="#gallery-3" class="control-button">•</a>
</div>
</div>
制作画册的图片以及描述信息等将放在figure标签中;用于点击的切换不同slide的按钮以一个圆点的形式放在<div class="controls"></div>
中,<a>
标签中以一个圆点作为按钮;div.control-operator并不显示,作控制用,后面会解释。
这里以3张图为例,添加slide只需要将以上的html代码对应扩展就可以了。
第一步基本布局设置
首先做一些全局设置,去掉body,figure标签的默认边距:
body,figure {
margin: 0;
}
设置img标签自动放缩:
img {
max-width: 100%;
height: auto;
}
接下来设置div.gallery及几个相关子元素的定位:
.gallery {
position: relative;
}
.gallery > .item {
position: absolute;
left: 0;
top: 0;
width: 100%;
text-align: center;
}
/* 设置包含<a>按钮的div块 */
.gallery > .controls {
position: absolute;
bottom: 0;
width: 100%;
text-align: center;
}
/* <a>按钮 */
.gallery .control-button {
display: inline-block;
margin: 0 .02em;
font-size: 3em;
text-align: center;
text-decoration: none;
}
.gallery > .item:first-of-type {
position: static;
}
.gallery > .control-operator {
display: none;
}
设置div.gallery为relative定位是为了让其子元素的absolute位置基于它自己。设置完以上属性,此时应该只能看到一张居中的图片,其余图片按顺序在下层被遮挡。
为什么要设置第一个figure.item定位为static
绝对定位意味着该元素将不复存在于正常的文档流中,如果div.gallery所有的子元素都绝对定位,div.gallery元素将无法被撑开,其高度将为0,设置其第一个figure.item子元素为static元素,意在撑开div.gallery,这样便于div.gallery中其他元素的显示,同时避免div.gallery后面的标签元素和div.gallery重叠。
第二步利用:target选择符控制图像的显示
为了让figure.item元素在没有被选中的时候消失,我们将其opacity属性设置为0,同时将第一个figure.item默认显示,修改添加以下代码:
.gallery > .item {
opacity: 0;
position: absolute;
left: 0;
top: 0;
width: 100%;
text-align: center;
}
.gallery > .item:first-of-ty