CSS定位总结:position=static/relative/absolute/fixed时的区别、top/bottom/left/right与margin外边距的运用

准备布局:

<!DOCTYPE html>
<html>
<head>
<style> 
*{ margin:0; padding:0; }
.base-container{
  width: 500px;
  height: 500px;
  background-color:lightgray;
  border:1px dashed red;
}
.base-compare {
  width:200px;
  height:100px;
  background-color:yellow;
  border:1px solid purple;
}
.base-parent {
  width:300px;
  height:230px;
  background-color:green;
}
.base-child {
  width:200px; // 宽高同.base-compare
  height:100px;
  background-color:cyan;
  border:1px solid purple;
}
</style>
</head>
<body>
<div class="base-container"><!--测试容器-->
  <div class="base-compare">我是参考div</div>
  <div class="base-parent parent"><!--父级div-->
      <div class="base-child child">我是子级div</div>
  </div>
</div>
</body>
</html>

(1)父级为relative,子级为absolute时:

.parent{
      position:relative;
}
.child{
      position:absolute;
      top:30px; // 如果是百分比%,则相对于父容器的高度的百分比
      left:20px;
      // margin-top:30px;  // 非%为单位时,等效,效果叠加;%为单位时,不等效! 
      // margin-left:20px; // 同上

}

(2)父级为static,子级为absolute时:

.parent{
  position:static;
}
.child{
  position:absolute;
  top:50px; // 50%; (单位为%和非%)都是相对于最近的relative容器而言
  margin-left: 50%; // 同上
}

(3)父级为fixed,子级为absolute时:

.parent{
  position:fixed;
}
.child{
  position:absolute;
  top:100%; // 相对于父容器的高度百分比
  right:10px; // 相对于父容器的右边
}

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值