CSS是一种独特的语言。乍一看,这似乎很简单,但是,某些在理论上看起来很简单的效果在实践中往往不那么明显。
在本文中,我将分享一些在大多数CSS教程中不太可能找到的有用技巧。
1. Sticky Footer
这个非常常见的需求,但对于初学者来说可能是个难题。
对于大多数项目,不管内容的大小,都希望页脚停留在屏幕的底部—如果页面的内容经过了视图端口,页脚应该进行调整。
在CSS3之前,如果不知道脚的确切高度,就很难达到这种效果。虽然我们称它为粘性页脚,但你不能简单地用 position: sticky
来解决这个问题,因为它会阻塞内容。
今天,最兼容的解决方案是使用 Flexbox。主要的做法是在包含页面主要内容的
div
上使用不太知名的 flex-grow
属性,在下面的示例中,我使用的是 main
标签。
flex-grow
控制 flex 项相对于其他 flex 元素填充其容器的数量。当值为 0
时,它不会增长,所以我们需要将它设置为 1
或更多。在下面的示例中,我使用了简写属性 flex: auto
,它将 flex-grow
默认设置为 1
。
为了防止任何不必要的行为,我们还可以在 footer
标签中添加 flex-shrink: 0
。flex-shrink
实际上与 flex-growth
属性相反,控制 flex 元素收缩到适合其容器的大小,将它设置为 0
刚防止 footer
标签收缩,确保它保留其尺寸。
// html
<div id="document">
<main>
<h1>Everything apart from the footer goes here</h1>
<p>Add more text here, to see how the footer responds!</p>
</main>
<footer>
<h1>The footer goes here</h1>
</footer>
</div>
web前端开发学习Q-q-u-n: 767273102 ,分享开发工具,零基础,进阶视频教程,希望新手少走弯路
// css
#document {
height: 100vh;
display: flex;
flex-direction: column;
}
main {
flex: auto;
}
footer {
flex-shrink: 0;
}
/* Other styling elements, that are not necessary for the example */
* {
margin: 0;
font-family: Candara;
}
h1, p {
padding: 20px;
}
footer {
color: white;
background: url(https://images.unsplash.com/photo-1550795598-717619d32900?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=676&q=80);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
footer > h1 {
text-shadow: 1px 1px 4px #00000080;
}
2. Zoom-on-Hover
zoom-on-hover 效果是将注意力吸引到可点击图像上的好方法。当用户将鼠标悬停在上面时,图像会稍微放大,但其尺寸保持不变。
为了达到这个效果,需要用 div
标签包裹 img
标签。
要使此效果生效,需要设置父元素的 width
和 height
,并确保将 overflow
设置为 hidden
,然后,你可以将任何类型的转换动画效果应用于内部图像。
// html
<div class="img-wrapper">
<img class="inner-img" src="https://source.unsplash.com/random/400x400" />
</div>
<!-- Additional examples -->
<div class="img-wrapper">
<img class="inner-img" src="https://source.unsplash.com/random/401x401" width="400px" height="400px" />
</div>
<div class="img-wrapper">
<img class="inner-img" src="https://source.unsplash.com/random/402x402" width="400px" height="400px" />
</div>
// css
.img-wrapper {
width: 400px;
height: 400px;
overflow: hidden;
}
.inner-img {
transition: 0.3s;
}
.inner-img:hover {
transform: scale(1.1);
}
3. 即时夜间模式
如果你正在寻找一个快速的方法来应用“夜间模式”皮肤到你的网站,可以使用 invert
和 hue-rotate
过滤器。