Fork me on GitHub

CSS总结

CSS实用代码汇总

多行文本未知高度垂直居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//css
*{margin:0;padding:0;}
.box{
height:200px;
width:300px;
background:pink;
margin:30px auto;
font-size:0;
}
.box:before{
content: '';
display: inline-block;
vertical-align: middle;
width: 0;
height: 100%;
}
.text{
display: inline-block;
font-size:16px;
vertical-align: middle;/* 保证文字垂直居中 */
}
//html
<div class="box">
<p class="text">
多行文本未知高度垂直居中-by 一丝多行文本未知高度垂直居中-by 一丝多行文本未知高度垂直 居中-by 一丝
</p>
</div>

实现原理:vertical-align的对齐是需要有参照物的,那么box 容器通过 before 生成一个高度 100% 的「备胎」,他的高度和容器的高度是一致的,相对于「备胎」垂直居中,在视觉上表现出来也就是相对于容器垂直居中了。

1
2
text-decoration:overline/underline/line-through/blink [浏览器不支持]
font-style:iatlic/oblique

斜体(italic)是一种简单的字体风格,对每个字母的结构有一些小改动,来反映变化的外观。倾斜(oblique)文本则是正常竖直文本的一个倾斜版本。 通常情况下,两种效果在浏览器中看上去完全一样。

如何让height100%起作用

我们都知道,要想让页面width:100%;可以通过直接设置width:100%实现,但如果是高度呢?直接设置height:100%;无法起作用。

这就需要我们理解浏览器的计算原理了。

事实上,浏览器根本就不计算内容的高度,除非内容超出了视窗范围(导致滚动条出现)。或者你给整个页面设置一个绝对高度。否则,浏览器就会简单的让内容往下堆砌,页面的高度根本就无需考虑。

但这并不意味着我们不能没有办法实现:

1
2
3
4
5
6
7
8
9
<html style="height: 100%;">
<body style="height: 100%;">
<div style="height: 100%;">
<p>
这样这个div的高度就会100%了
</p>
</div>
</body>
</html>

可以通过给html,body设置height:100%;实现。但随之也带了一系列问题:

  1. Margins 和 padding 会让你的页面出现滚动条,也许这是你不希望的。
  2. 如果你的元素实际高度大于你设定的百分比高度,那元素的高度会自动扩展。

文字溢出隐藏并显示省略号。

1
overflow:hidden; white-space:nowrap; text-overflow:ellipsis;

自定义文本选中

1
2
::selection{color:#fff; background:#333;}
::-moz-selection{color:#fff;background:#333;}

引用自定义字体

1
2
3
4
5
@font-face
{
font-family: xujinglei; src: url('xujinglei.ttf'),url('xujinglei.eot'); //IE9+
}
div{font-family:xujinglei; font-size:18px; }

常用标题

title

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<h2 class="title" data-text="hello world"></h2>
.title{
width:1000px;
margin:20px auto;
position:relative;
}
.title:before{
content:'';
display:block;
border-top:1px solid #ccc;
}
.title:after{
content:attr(data-text);
display:block;
position:absolute;
padding:0 20px;
background:#fff;
color:#666;
top:0;
left:50%;
transform:translate(-50%,-50%);
}
//less写法
.title(@bg:white){
width:1000px;
margin:20px auto;
position:relative;
text-transform:uppercase;
white-space:nowrap;
&:before{
content:'';
display:block;
border-top:1px solid #ccc;
}
&:after{
content:attr(data-text);
position:absolute;
top:0;
left:50%;
padding:0 20px;
background:@bg;
transform:translate(-50%,-50%);
}
}

据说帅的人都赏给博主几块钱零花钱。