1. CSS 基础概念
样式:文字样式、盒模型的样式
布局:辅助页面布局,完成HTML不能完成的功能,如并排显示,精确定位显示。
前端三层
- 结构层:HTML从语义的角度进行网页结构的搭建
- 样式层:CSS从美观的角度修饰页面样式
- 交互层:JS从交互的角度描述页面的行为
2. CSS的常用样式属性
-
字体属性:color, font-size, font-family
- color可为rgb、16进制色等。
- chrome字体默认16px, 最小8px。
- 中文常用微软雅黑、宋体;英语常用Arial、consolas。
<p style=" color: #0000FF; font-size: 20px; font-family: 'consolas','宋体'">字体, text</p>
-
文本属性:text-align, text-decoration, text-indent
- text-align: left / center / right
- text-decoration: overline / line-through / underline
- text-indent: 10px / 10% / 2em
-
盒子属性:width, height, background-color
<p style=" width: 10px; height: 10px; background-color: red">文字, text</p>
3. 背景属性
3.1 背景属性
-
背景样式
background-color: rgba();
background-image: url(images/1.png)
- 背景覆盖范围:width、height、padding、border
- 若设置背景颜色,背景图会在border内覆盖显示。
-
背景重复
background-repeat: no-repeat
background-repeat: repeat-x
background-repeat: repeat-y
- 利用重复特性实现渐变色背景
-
背景定位
background-position: left top;
background-position: center center;
- 盒子的宽高固定且小于背景图,默认显示左上角部分背景图,建议展示居中区域。
- 网页中设置顶部居中的banner大图片
background-position: 1px 1px;
- 图片距离左上角的坐标。
- 像素值px可以为负数。
background-position: 50% 50%;
- 0%,0%在盒子左上角; 100%,100%在盒子右下角。
-
背景附着
background-attachment: scroll;
background-attachment: fixed;
- 背景图是否跟随页面滚动。
-
综合属性
background: url(images/1.png) no-repeat center top scroll cyan;
- 属性值1~5个,属性书写顺序可以颠倒。
3.2 场景应用
-
点击logo图片跳转:
<style> h1 { width: 500px; overflow: hidden; } h1 a { display: block; height: 50px; width: 100px; background: url(logo.png) no-repeat; text-indent: -10em; } </style> <h1> <a href="https://www.baidu.com">logo</a> </h1>
-
利用padding插入背景
<style> ul { list-style: none; line-height: 30px; } ul li { padding-left: 20px; background: url(start.png) no-repeat center left; } </style> <ul> <li>文字文字文字文字文字文字</li> <li>文字文字文字文字文字文字</li> <li>文字文字文字文字文字文字</li> </ul>
-
背景精灵
从汇集了许多icon的背景图中截出所需的icon<style> div { width: 100px; height: 10px; margin: 100px auto; } div p { width: 10px; height: 10px; float: left; margin: 0 5px; background: url(icons.png) no-repeat 0px 0px; } p.para1 { background-position: -10px -10px; } p.para2 { background-position: -20px -20px; } </style> <div> <p class="para1"></p> <p class="para1"></p> </div>
3. CSS样式表的引入
3.1 行内式:
<div style="color:red; font-size;"> </div>
3.2 内嵌式:
<head>
<title>style要在title下面</title>
<style>
div {color:red; font-size;}
</style>
</head>
3.3 外链式:
<head>
<title>link要在title下面</title>
<link rel="stylesheet" href="css/1.css">
</head>
3.4 导入式:
<head>
<style>
@import url(css/1.css);
div {color:red; font-size;}
</style>
</head>
导入式不常用,import要写在style中的最顶部
4. CSS引入的优先级
样式表 | 优先级 | 优点 | 缺点 |
---|---|---|---|
行内式 | 高 | 样式设置更精确 | 1.结构样式未分离 不2.能批量修改样式 |
内嵌式 | 中 | 可批量修改样式 | 1.结构样式未完全分离 2.多个html文件不能用同一套css代码 |
外链式 | 中 | 样式和骨架完全分离 | 写起来麻烦,看起来不直观 |
导入式 | 低 | 样式和骨架完全分离 | 涉及到加载顺序,加载体验差 |