css中position的定义

本文通过两个实例详细解析了CSS中absolute和relative定位方式的使用方法。第一个实例展示了如何使用absolute定位使元素相对于其最近的已定位父元素进行偏移。第二个实例则解释了relative定位下元素如何相对于其正常位置进行偏移。

1.absolute:

<html>
<head>
<title>position</title>
<style>
#father {
	width:200px;
	height:100px;
	position:reletive;
	background-color:blue;
}
#son {
	width:100px;
	height:50px;
	position:absolute;
	background-color:gray;
	top:20px;
	left:40px;
}
</style>
</head>
<body>
	<div id="father">
		<div id="son">son</div>
	</div>
</body>
</html>

上面代码块中,son设置了position为absolute,father设置了position为relative,则会出现son相对father向下20px,向右偏40px;


2.

<html>
<head>
<title>position</title>
<style>
#father {
	width:100%;
	height:100%;
	background-color:blue;

}

#son {
	width:100px;
	height:50px;
	position:relative;
	background-color:gray;
	top:10%;
	left:40px;

}
</style>

</head>
<body>
	<div id="father">
		<div id="son">son</div>
	</div>
</body>
</html>
上面的代码,son的position设置了relative,同事top为10%,则无论页面高度为多少,son始终距离son应该在的位置下方10%,fature没有设置padding,son没有设置magin,则10%应该是距离father最顶端10%,左右也是如此。




### CSS `position: fixed` 使用方法 #### 定义与特性 `position: fixed` 是一种用于固定定位的方式,被设置为该属性的元素会被锁定到浏览器窗口上的某个位置[^1]。无论页面如何滚动,这个元素都会保持在指定的位置不变。 当使用 `position: fixed` 时,默认情况下它是相对于整个视口(viewport)来定义其位置的。然而,如果它的父级容器应用了一些特定的样式(如 `transform`, `perspective`, 或者 `filter`),那么它将会相对这些具有特殊样式的父级容器进行定位[^2]。 #### 基本语法 以下是基本的 CSS 语法规则: ```css .element { position: fixed; top: value; /* 距离顶部的距离 */ right: value; /* 距离右侧的距离 */ bottom: value; /* 距离底部的距离 */ left: value; /* 距离左侧的距离 */ } ``` 其中 `value` 可以为具体的长度单位 (px, em, % 等),也可以是关键字 auto 来表示自动计算距离[^3]。 #### 示例代码 下面是一个简单的例子展示如何利用 `position: fixed` 创建一个始终位于屏幕右上角 50px 处的小提示框: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Fixed Position Example</title> <style> .fixed-box { position: fixed; top: 50px; /* 设置距顶边50像素 */ right: 50px; /* 设置距右边50像素 */ width: 200px; height: 100px; background-color: lightblue; border: 1px solid blue; text-align: center; line-height: 100px; } </style> </head> <body> <div class="fixed-box">我是固定的盒子!</div> <p style="height: 2000px;">向下滚动查看效果...</p> </body> </html> ``` 在此示例中,`.fixed-box` 将一直停留在视图的右上方,即使用户上下拖动网页也不会改变其位置。 #### 特殊情况下的行为调整 需要注意的是,尽管通常 `position: fixed` 的对象会依据整个文档的视窗作为参照物,但如果存在祖先节点设置了诸如 `transform`, `perspective`, 或 `filter` 这样的非默认值,则目标元素可能会基于最近的一个这样的祖先节点来进行定位而不是全局视窗。 例如: ```css .parent { transform: translateX(0); } .child { position: fixed; top: 0; left: 0; } ``` 在这种场景下 `.child` 并不会严格遵循整体视窗而是可能受到 `.parent` 影响而有所偏移。 ### 结论 通过上述介绍可以看出,`position: fixed` 提供了一种非常强大的方式去控制某些 UI 组件在整个浏览体验期间维持稳定可见状态的能力。不过也要注意特殊情况下的表现差异以便更好地实现预期设计效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值