CSS:层叠样式表,通过样式定义如何显示HTML标签,将内容的显示与表现进行了分离,提高了工作的效率。
使用CSS设置样式时,首先需要通过选择器获取到标签信息,然后才能对标签设置属性信息。
普通选择器
- id选择器:标签中设置id属性,样式中用“#”代表id选择器。
- 类选择器:标签中设置class属性,样式中用“.”代表类选择器。
- 标签选择器:样式中使用某一标签名代表该标签的选择器。
<style type="text/css">
#id1{
font-size: 14px;
}
.className{
color: red;
}
h{
line-height: 20px;
}
</style>
复合选择器
- 选择器分组:以“,”分隔将任意多个选择器分组在一起,样式中的设置是对所有选择器共同的设置。
- 后代选择器(也称包含选择器):以空格分隔选择器,左边的选择器包含右边的选择器,具有这种结构的最右边的选择器会被设置样式。
- 属性选择器:使用[]中括号括起来的属性,具有括号中属性的标签会被设置样式。
<style type="text/css">
h,p,div{
font-size: 18px;
}
div span{
color: red;
}
a[class]{
text-decoration: none;
}
</style>
框模型
在CSS中将HTML的每一个标签都看做一个个的盒子,每个盒子都具有边框和边距。
- 内边距 padding。
- 边框 border。
- 外边距 margin。
<style type="text/css">
div{
border: 1px solid black;
margin: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
margin-botton: 0px;
padding: 1px;
padding-left: 1px;
padding-right: 1px;
padding-top: 1px;
padding-botton: 1px;
}
</style>
字体属性
- 字体家族 font-family:设置字体类型,如“宋体”,可以设置多个类型。
- 字体风格 font-style:设置是否为斜体,一般使用值 italic。
- 字体加粗 font-weight:设置字体粗细,若值为 bold 则表示加粗。
- 字体大小 font-size:设置字体大小。
<style type="text/css">
div{
font-family: "宋体";
font-style: italic;
font-weight: bold;
font-size: 18px;
}
</style>
文本属性
- 文本对齐 text-align, vertical-align:水平对齐和垂直对齐。
- 文本缩进 text-indent:设置文本缩进,em表示字符单位。
- 行高 line-height:设置行高。
- 文本装饰 text-decoration:设置文本下划线、顶线、对穿线等。
<style type="text/css">
div{
text-align: center;
vertical-align: middle;
text-indent: 2em;
line-height: 20px;
text-decoration: underline/overline/none/...;
}
</style>
颜色与背景属性
- 字体颜色 color:设置字体颜色。
- 背景颜色 background-color:设置背景颜色。
- 背景图片 background-image:设置背景图片。
- 背景图片平铺 background-repeat:但背景图片太小时会默认以平铺的方式弥补空白位置,可以设置是否需要平铺或以何种方式平铺,可以水平平铺或垂直平铺。
- 背景图片放置位置 background-position:设置图片放置的坐标(左上角)
<style type="text/css">
div{
color: green;
background-color: yellow;
background-image: url("../...jpg");
background-repeat: none/repeat-x/repeat-y;
background-position: 100px 100px;
}
</style>
列表属性
- 列表项的外形显示 list-style-tyle:设置列表左侧的标记形式。
<style type="text/css">
ul{
list-style-tyle: none;
}
</style>
显示属性 display
- 块级元素 block。
- 行级元素 inline。
- 不显示 none。
<style type="text/css">
div{
display: none/block/inline;
}
</style>
浮动 float
- 左浮动 left。
- 右浮动 right。
<style type="text/css">
ul{
float: right;
}
ul li{
float: left;
}
</style>
溢出处理 overflow
当标签内的内容溢出时处理:
- scroll:溢出后显示拖动条。
- hidden:隐藏,溢出的部分将不会显示。
- auto:自动。
<style type="text/css">
#div1{
overflow: scroll/hidden/auto;
}
</style>
清除浮动 clear
浮动会使标签脱离父标签的约束,在设置完浮动后清除浮动可以使标签返回到父标签中,且浮动效果不变。
- left:清除左浮动。
- right:清除右浮动。
- both:清除左右浮动。
<style type="text/css">
#div1{
float: left;
}
#div2{
clear: left;
float: left;
}
</style>
元素定位 position
- relatiive:相对定位。
- absolute:绝对位置。
<style type="text/css">
ul{
position: relative;
}
#li_1{
position: absolute;
top: 10px;
left: 10px;
}
</style>