CSS Hack
学习目标
CSS初始化
因为默认样式导致的错乱问题,而且每个浏览器的CSS默认样式不尽相同,所以最简单有效的方式就是对其进行初始化(覆盖默认样式)。
*{
margin: 0;
padding: 0;
}
关于浏览器CSS样式初始化,经验不丰富的话,推荐一个库给大家,Normalize.css,github star数量接近4万,自行选取展示其中几个样式设置,如下:
html {
line-height: 1.15; /* Correct the line height in all browsers */
-webkit-text-size-adjust: 100%; /* Prevent adjustments of font size after orientation changes in iOS. */
}
body {
margin: 0;
}
a {
background-color: transparent; /* Remove the gray background on active links in IE 10. */
}
img {
border-style: none; /* Remove the border on images inside links in IE 10. */
}
CSS hack
除了以上的默认样式覆盖及私有属性添加,有时我们还需要针对不同的浏览器甚至不同版本编写特定的CSS样式,这一过程就叫做CSS hack。
CSS hack的写法大致可以归纳为以下几种:条件hack、属性级hack、选择符级hack。
条件hack:主要针对IE浏览器进行一些特殊的设置
<!--[if <keywords>? IE <version>?]>
代码块,可以是html,css,js
<![endif]-->
关键词
if后面跟的条件共包含6种选择方式:是否、大于、大于或等于、小于、小于或等于、非指定版本。
- 是否:指定是否IE或IE某个版本。关键字:空。
- 大于:选择大于指定版本的IE版本。关键字:gt(greater than)。
- 大于或等于:选择大于或等于指定版本的IE版本。关键字:gte(greater than or equal)。
- 小于:选择小于指定版本的IE版本。关键字:lt(less than)。
- 小于或等于:选择小于或等于指定版本的IE版本。关键字:lte(less than or equal)。
- 非指定版本:选择除指定版本外的所有IE版本。关键字:! 。
IE浏览器版本,如6、7、8,但IE10及以上版本已将条件注释特性移除,使用时需注意。
示例:
<!--[if IE]>
<p>你在非IE中将看不到我</p>
<![endif]-->
<!--[if IE]>
<style>
.test{color:red;}
</style>
<![endif]-->
<!--[if lt IE 9]>
<script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->