css伪元素与行内/行内块元素的margin-top问题简答

伪元素

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值