伪元素
CSS伪元素用于向某些选择器设置特殊效果
语法:
selector:pseudo-element {property:value;}
css常见的伪元素:
:first-line:为对象内的第一行设置样式
实例:
<html>
<head>
<style>
p:first-line{
color:red;
}
</style>
<p>Hello<br />你好</p>
<body>
</body>
</html>
运行结果:
注释:“first-line” 伪元素只能用于块级元素。
:first-letter:为对象内的第一个字符设置样式
实例:
<html>
<head>
<style>
p:first-letter{
color:lightskyblue;
}
</style>
<p>你好世界</p>
<body>
</body>
</html>
运行结果:
:before:用来在元素的内容前面插入新内容
实例:
<html>
<head>
<style>
p:before{
content:"你好 ";
}
</style>
<p>World</p>
<body>
</body>
</html>
运行结果:
:after:用来在元素的内容之后插入新内容。
实例:
<html>
<head>
<style>
p:after{
content:" 世界";
}
</style>
<p>Hello</p>
<body>
</body>
</html>
运行结果:
行内元素
关于行内元素的margin-top问题
行内元素一般是内容的容器,块级元素一般是其他容器的容器。一般情况下,行内元素只能包含内容或者其它行内元素,宽度和长度依据内容而定,不能设置,可以和其它元素和平共处于一行。
如果想设置margin-top/bottom需要转换为行内块元素。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 200px;
height: 200px;
border: 1px solid #000;
}
.w{
display: inline-block;
margin-top: 30px;
background-color: yellow;
}
</style>
<body>
<div class="box">
<span class="w">这是span行内元素标签</span>
</div>
</body>
</html>
另一种方法 添加transform属性
示例:
<style>
.box{
position: relative;
width: 300px;
height: 100px;
border: 1px solid #000;
}
.w{
display: inline-block;
transform: translate(20px,20px);
background-color: yellow;
}
</style>
<body>
<div class="box">
<a href="#">超链接</a><span class="w">span元素加了transform: translate属性</span>
</div>
</body>
</html>