css3定位属性:top,bottom,left,right

css3定位属性

top,bottom,left,right

  • 取值:auto,,
  • 默认值:auto
  • 继承性:无
说明
  1. 定义了元素的上外边距边界(外margin)与其包含块上边界(外padding)之间的偏移距离,取值可以为负值;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
  padding: 0;
  margin:0;
}
.parent1{
  width:100px;
  height:100px;
  position:relative;
  padding: 10px;
  margin:20px;
  border: 15px solid #ddd;
}
.child1{
  width:20px;
  height: 20px;
  top:30px;
  position:absolute;
  padding: 10px;
  margin:20px;
  border: 25px solid #ccc;
}
</style>
</head>
<body>
  <div class="parent1">
    <div class="child1"></div>
  </div>
</body>
</html>
  1. 当position为static时,计算值是auto。为relative时,如果top和bottom都是auto,则它们的计算值是0;如果top和bottom其中一个为auto,则auto相当于另一个的负值,即top=-bottom;如果top和bottom的值都不为auto,则忽略bottom(left和right)。

注意:

  • 绝对定位的布局取决于三个因素,一个是元素的位置,一个是元素的尺寸,一个是元素的margin值。
  • 没有设置尺寸和 margin的元素会自适应剩余空间,位置固定则分配尺寸,尺寸固定边会分配 margin,都是自适应的。

利用上述特性,我们可以利用有如下的方法实现元素的水平垂直居中效果。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
  padding: 0;
  margin:0;
}
.parent1{
  width:100px;
  height:100px;
  position:relative;
  border: 1px solid #ddd;
}
.child1{
  width:20px;
  height: 20px;
  background-color: red;
  position:absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto; //后面六个css属性中,position:absolute,margin:auto不能缺少,如果只有top和bottom,则只能实现垂直居中;如果只有left和right,则只能实现水平居中;如果四个都有,能够实现水平垂直居中
}
</style>
</head>
<body>
  <div class="parent1">
    <div class="child1"></div>
  </div>
</body>
</html>

参考链接:

  1. http://css.doyoe.com/
  2. https://www.barretlee.com/blog/2014/08/07/position-and-margin/
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值