css(层叠样式表)是网页设计的基石,控制着网页的视觉呈现。虽然 css 功能强大,但有时您需要采用巧妙的技巧或“技巧”来实现某些效果或确保不同浏览器之间的兼容性。这里有一些有用的 css 技巧的指南,可以拯救你的一天。
1. 针对特定浏览器
internet explorer (ie) 特定黑客攻击
ie 一直因渲染问题而臭名昭著。以下是针对不同版本 ie 的方法:
/* ie 10 and 11 */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.selector {
property: value;
}
}
/* ie 6-10 */
* html .selector {
property: value;
}
/* ie 7 */
*:first-child+html .selector {
property: value;
}
/* ie 8 */
html>/**/body .selector {
property: value;
}
/* ie 9 */
_:-ms-fullscreen, :root .selector {
property: value;
}
针对火狐
/* firefox */
@-moz-document url-prefix() {
.selector {
property: value;
}
}
针对 chrome
/* chrome */
@media screen and (-webkit-min-device-pixel-ratio:0) {
.selector {
property: value;
}
}
2. 使用 css hack 解决常见问题
清除浮动
浮动会导致父元素崩溃。这是清除浮动的快速技巧:
/* clearfix hack */
.clearfix::after {
content: "";
display: table;
clear: both;
}
将此类应用于任何带有浮动子项的容器。
等高柱
flexbox 是现代解决方案,但这里有一个针对旧版浏览器的技巧:
/* equal height columns */
.parent {
display: flex;
}
.child {
flex: 1;
}
居中元件
水平居中块元素:
/* horizontal centering */
.selector {
margin: 0 auto;
}
垂直居中元素:
/* vertical centering */
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translatey(-50%);
}
3.响应式设计技巧
响应式文本
使用视口单位使文本大小响应:
/* responsive text */
.selector {
font-size: 4vw; /* 4% of the viewport width */
}
媒体查询黑客
使用媒体查询定位特定的屏幕尺寸:
/* media queries */
@media (max-width: 600px) {
.selector {
property: value;
}
}
@media (min-width: 601px) and (max-width: 1200px) {
.selector {
property: value;
}
}
4. 高级 css hack
使用 :not() 伪类
隐藏除第一个子元素之外的元素:
/* :not() hack */
.selector:not(:first-child) {
display: none;
}
纯 css 工具提示
无需 javascript 创建工具提示:
/* CSS Tooltips */
.tooltip {
position: relative;
display: inline-block;
cursor: pointer;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 125%; /* Position the tooltip */
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
结论
css hack 对于解决棘手的布局问题、确保浏览器兼容性和创建响应式设计非常有用。虽然现代 css 和 flexbox 和 grid 等工具减少了许多黑客的需要,但在某些情况下了解这些技术仍然可以成为救星。请记住,明智地使用 hack,并且始终首先以干净、可维护的代码为目标。快乐编码!