CSS中相对定位relative

本文介绍了CSS中的相对定位概念,解释了相对定位如何让元素在其起点基础上移动,同时强调了即使移动,元素仍占据原有空间,可能导致覆盖其他元素。通过代码示例展示了相对定位对文档流的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-------------------------------------------CSS中相对定位relative-----------------------------------

 

相对定位

相对定位是一个非常容易理解的概念,如果对一个元素先对定位,可以设置其水平位置和垂直位置,这个元素相对于元素的起点开始移动。

注意:在使用相对定位的时候无论是否进行移动,元素仍然会占据原有的空间,因此移动元素可能覆盖其他元素。

 

代码示例:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style type="text/css">

body{

    margin:10px;

    font-size:12px;

    font-family:Arial;

}

.outside{

    width:1000px;

    height:600px;

    background-color:#a9d6ff;

    border:1px dashed black;

}

 

.inside{

    padding:10px;

    background-color:#fffcd3;

    border:1px dashed black;

    margin: 10px;

}

 

.inside1{

    margin:10px;

    padding: 10px;

    background-color:#fffcd3;

    border:1px dashed black;

    /* 设置相对定位 ,相对点是当前div的原始位置的左上角*/

    position: relative;

    /* 距离div的原始位置的左边框 */

    left:20px;

    /* 距离div的原始位置的上边框 */

    top:30px;

    /*

       right距离div的原始位置的右边框

       bottom距离div的原始位置的下边框

    */

}

</style>

</head>

<body>

<div class="outside">

    <div class="inside">div1</div>

    <div class="inside1">div2</div>

</div>

</body>

</html>

-----------------------------------------------------------------

相对定位对文档流的影响

代码示例:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style type="text/css">

body{

    margin:10px;

    font-size:12px;

    font-family:Arial;

}

.outside{

    width:1000px;

    height:600px;

    background-color:#a9d6ff;

    border:1px dashed black;

}

 

.inside{

    padding:10px;

    background-color:#fffcd3;

    border:1px dashed black;

    margin: 10px;

    position:relative;

    left:30px;

    top:30px;

    /* div1相对定位脱离了文档流,

        但是后续的div还会认为div1是在没有相对定位之前的状态

        所有后续的div不会填补div1的空缺位置,而是继续按照文档流来排序    

    */

}

 

.inside1{

    margin:10px;

    padding: 10px;

    background-color:#fffcd3;

    border:1px dashed black;

}

</style>

</head>

<body>

<div class="outside">

    <div class="inside">div1</div>

    <div class="inside1">div2</div>

</div>

</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值