标签:它的 border 行内元素 取消 包含 的区别 relative size 垂直
在 CSS 中,position 属性指定一个元素(静态的,相对的,绝对或固定,以及粘性定位)的定位方法的类型。
当设置 position 属性的值为 absolute 时,生成绝对定位的元素,将该元素从文档流中删除,原来的占位不再存在,并相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。
border-box。<html>。.box {
position: relative;
margin: 0 auto;
padding: 10px;
width: 300px;
height: 200px;
background: rgb(66, 98, 104);
}
.box-item {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background: rgb(65, 116, 126);
}
position 为 absolute 的元素如果没有设置 left, top 等值与 left:0; top:0; 的的效果一样吗?
答案是不一样的,一个没有设置 left 和 right 值的绝对定位的元素就像是一个行内块元素,其表现得依旧在 DOM tree 中,对 margin 等属性敏感,但是其实际宽高已经丢失,如果没有设置高度,则其高度由其中的内容决定。
.box {
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: rgb(66, 98, 104);
}
.container {
margin: 0 auto;
width: 100px;
height: 100px;
background: rgb(68, 155, 172);
}
.box-item {
position: absolute;
width: 20%;
height:20%;
background: rgb(65, 116, 126);
}
对于设置了 left:0; top:0; 的绝对定位的元素,这个元素将会从 DOM 树中脱离,独立于文档流,然后会根据相对于 static 定位以外的第一个父元素进行定位。
所以没有定位值的 absolute 元素可以说是个更加变态(没有实际宽度)的 float 元素(实际占据高度为 0),所以浮动元素干的某些事情绝对定位元素也能做到。
CSS 设置绝对定位后 top,bottom 设置百分比定位是按父元素的高度来计算的,同样 left,right 设置百分比定位是按父元素的宽度度来计算的。
.box {
position: relative;
margin: 0 auto;
width: 300px;
height: 200px;
background: rgb(66, 98, 104);
}
.box-item {
position: absolute;
top: 10%;
left: 10%;
width: 100px;
height: 100px;
background: rgb(65, 116, 126);
}
如果父元素设置有 padding 值,则子元素定位 top,bottom 设置百分比定位是按父元素的高度 + 垂直内边界来计算的,同样 left,right 设置百分比定位是按父元素的宽度 + 水平内边界来计算的。
/* box-sizing: content-box; */
.box {
position: relative;
margin: 0 auto;
padding: 10px 20px;
width: 200px;
height: 200px;
background: rgb(66, 98, 104);
}
.box-item {
position: absolute;
top: 10%;
left: 10%;
width: 100px;
height: 100px;
background: rgb(65, 116, 126);
}
当 box-sizing: border-box; 时,其计算与内边界无关。
如果父元素设置有 border 值,则子元素定位设置的百分比定位值的计算与边框无关。
/* box-sizing: content-box; */
.box {
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: rgb(66, 98, 104);
border: 10px solid rgb(117, 141, 145);
}
.box-item {
position: absolute;
top: 10%;
left: 10%;
width: 100px;
height: 100px;
background: rgb(65, 116, 126);
}
当 box-sizing: border-box; 时,如果父元素设置有 border 值,则子元素定位 top,bottom 设置百分比定位是按父元素的高度 - 垂直边框来计算的,同样 left,right 设置百分比定位是按父元素的宽度 - 水平边框来计算的。
绝对定位元素的百分比宽高是相对于其最近的父级别定位元素的 padding-box 的大小来计算的。
/* box-sizing: content-box; */
.box {
position: relative;
margin: 0 auto;
padding: 20px;
width: 200px;
height: 200px;
background: rgb(66, 98, 104);
border: 10px solid rgb(117, 141, 145);
}
.container {
margin: 0 auto;
width: 100px;
height: 100px;
background: rgb(68, 155, 172);
}
.box-item {
position: absolute;
top: 0;
left: 0;
width: 20%;
height:20%;
background: rgb(65, 116, 126);
}
当 box-sizing: border-box; 时,依然遵循上面的原则,所以计算绝对定位元素的百分比宽高时,应由 height - border 作为基础。
若是文中有什么错误,欢迎大家指正,希望和大家在交流之中共同进步。
标签:它的 border 行内元素 取消 包含 的区别 relative size 垂直
原文地址:https://www.cnblogs.com/anani/p/9462927.html