设置position为absolute或fixed之后,子元素设置width 100%造成宽度溢出的问题

3个div:

<div class="parent">
某人
    <div class="child">
	儿子
		<div class="grandson">孙子</div>
    </div>
</div>

css 样式:

.parent {
	width: 700px;
	height: 600px;
	background-color: rgba(97, 166, 255, 1.0);
}

.child {
	width: 50%;
	height: 500px;
	background-color: rgba(245, 255, 148, 0.5);
}

.grandson {
	position: absolute;
	width: 100%;
	height: 50px;
	background-color: aquamarine;
    bottom: 0;
}

页面效果

原因:绝对定位时,参照物是最近的position为非static的元素。

验证:设置某人的position为relative:

.parent {
	position: relative;
	width: 700px;
	height: 600px;
	background-color: rgba(97, 166, 255, 1.0);
}

 这时候孙子就相对于某人进行定位

所以当你想要基于最近的父元素进行相对定位时,需要给它设置position为非static。

定位(position):

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

  • relative: 该关键字下,元素先放置在未添加定位时的位置,再在不改变页面布局的前提下调整元素位置(因此会在此元素未添加定位时所在位置留下空白。

  • absolute: 元素会被移出正常文档流,且不为元素预留空间,它相对于它最近的非 static 定位(未设置就是 static) 的父元素的偏移来确定元素位置。且它所继承的宽高尺寸也是如此。

    绝对定位的元素可以设置外边距(margins),且不会与其他外边距合并。

  • fixed: 生成绝对定位的元素,相对于浏览器窗口进行定位。 元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

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

猜你喜欢

转载自blog.csdn.net/fqqbw/article/details/127710439