html 图片position,【图解CSS#Position】

关于CSS position,来自MDN的描述:

CSS position属性用于指定一个元素在文档中的定位方式。top、right、bottom、left 属性则决定了该元素的最终位置。

先看一个图片:

22f35be72f2a

child没设置position的样式

代码如下:

child1-1
child1-2
child1-3
child1-4

.parent1{

background-color: chocolate;

width: 300px;

height: 300px;

margin: 25px 50px 75px;

}

.child1-1{

background-color: cornflowerblue;

width: 60px;

height: 60px;

}

.child1-2{

background-color:crimson;

width: 60px;

height: 60px;

}

.child1-3{

background-color:darkcyan;

width: 60px;

height: 60px;

}

.child1-4{

background-color: darkgreen;

width: 60px;

height: 60px;

}

这里展示的就是一个正常“文档流”,

Normal flow

Boxes in the normal flow belong to a formatting context, which may be block or inline, but not both simultaneously. Block-level boxes participate in a block formatting context. Inline-level boxes participate in an inline formatting context.

个人理解:顾名思义就是像写文档一样,一行一行的排列,如图,每个child 都是一个60*60 的小方块,即使在他们右边有多余的位置,但是它们还是占一行。position就是每个元素的定位属性,而默认就是 position = static,即上图中parent 和 child 都是展示的文档流样式。

而position属性一共有以下取值:

static

默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)

relative

生成相对定位的元素,相对于其正常位置进行定位。 如我们将上面的代码改成

// ...

.child1-2{

background-color:crimson;

width: 60px;

height: 60px;

position: relative;

left: 20px;

top: 30px;

}

22f35be72f2a

relative

可以看到 child1-2 在原来的位置上,左边多出了 20px ,距离顶部多出了 30px

absolute

生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。

我们将上例的child1-2恢复,然后操作child1-3

.child1-3{

background-color:darkcyan;

width: 60px;

height: 60px;

position: absolute;

left: 20px;

top: 30px;

}

22f35be72f2a

absolute

可以看到,child1-3 的位置已经和 parent 无关了(因为 parent 的 position = "static"),很多时候,都会将 parent 设置成relative 来和 absolute child 配合使用。

我们再改一下 child1-3 的代码

.child1-3{

background-color:darkcyan;

width: 60px;

height: 60px;

position: absolute;

left: 20px;

bottom: 30px; // 注意这个

}

22f35be72f2a

bottom 30px

22f35be72f2a

bottom 30px 增加浏览器的高度

可以看到,child1-3 其实是一直跟着浏览器的高度在变化的。

fixed

.child1-4{

background-color: darkgreen;

width: 60px;

height: 60px;

position: fixed;

bottom: 30px;

left: 70px;

}

22f35be72f2a

fixed

而且,当浏览器高度变化时,他们两个也会跟着变化。

但是,两者的区别就在于,当 parent 设置成 position = relative 时,

.parent1{

background-color: chocolate;

width: 300px;

height: 300px;

margin: 25px 50px 75px;

position: relative;

}

22f35be72f2a

parent position = relative

即此时,child1-3 的 left,right 等以 parent 为基准。

inherit

规定应该从父元素继承 position 属性的值。

这个就不需要图解了。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值