分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

关于对CSS ?position的理解

发布时间:2023-09-06 02:15责任编辑:彭小芳关键词:CSS

CSS的position属性的关键字分别是static、relative、absolute、fixed、sticky。

static

static根据文档的正常流进行定位。对top、right、bottom、left、z-index属性没有影响。这是默认值。

如图所示:

relative

relative根据文档的正常流进行定位,根据top、right、bottom、left的值相对于自身进行偏移。

效果图

HTML

<!DOCTYPE html><html> ???<head> ???????????<meta charset="utf-8"> ???????????<title>relative</title> ???????????<link href="relative.css" rel="stylesheet" type="text/css" > ???</head> ???<body> ???????????<div class="box" id="one">One</div> ???????????<div class="box" id="two">Two</div> ???????????<div class="box" id="three">Three</div> ???????????<div class="box" id="four">Four</div> ???????</body></html>

CSS

.box { ???display: inline-block; ???width: 100px; ???height: 100px; ???background: red; ???color: white; ?} ???#one { ???position: relative; ???top: 40px; ???left: 40px; ???background: blue; ?}

  

absolute

该元素位置相对于已定位的最近的父元素,若父元素不在,则相对于ICB(初始包含块)。absolute定位的元素与其它元素重叠。

效果

HTML

<!DOCTYPE html><html> ???<head> ???????????<meta charset="utf-8"> ???????????<title>absolute</title> ???????????<link href="absolute.css" rel="stylesheet" type="text/css" > ???</head> ???<body> ???????????<h1>展示absolute的用法。</h1> ???????????<p>这是第一段。</p> ???????????<p class="positioned">哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈啊哈。。。 </p> ???????????<p>kkkkkkkkkkkkkkkkkk。。。</p> ???????????<p>凑字数 <span>不凑字数</span> 凑字数<span>不凑字数</span> 凑字数</p> ???????</body></html>

CSS

p { ?background: aqua; ?border: 3px solid blue; ?padding: 10px; ?margin: 10px;}span { ?background: red; ?border: 1px solid black;}.positioned { ?position: absolute; ?background: yellow; ?top: 30px; ?left: 30px;}

fixed

使用fixed属性,即使页面滚动,元素也不会移动。

CSS

.box { ?width: 100px; ?height: 100px; ?background: red; ?color: white;}#one { ?position: fixed; ?top: 80px; ?left: 10px; ?background: blue;}.outer { ?width: 500px; ?height: 300px; ?overflow: scroll; ?padding-left: 150px;}

  

sticky

顾名思义,元素就像粘着一样。依赖用户的滚动行为在“relative”和“fixed”之间切换。

它必须指定一个阈值(top、right、bottom、left至少其中一个)来使粘滞定位按预期方式进行,否则无法与相对定位区分。

HTML

<!DOCTYPE html><html><head><meta charset="utf-8"> <title>展示sticky元素用法</title> <style>div.sticky { ?position: -webkit-sticky; ?position: sticky; ?top: 0; ?padding: 10px; ?background-color: #cae8ca; ?border: 2px solid #4CAF50;}</style></head><body><p>滚动页面。</p><div class="sticky">sticky</div><div style="padding-bottom:2000px"> ?<p>roll</p> ?<p>roll</p> ?<p>roll</p> ?<p>roll</p> ?<p>roll</p> ?<p>roll</p></div></body></html>

关于对CSS ?position的理解

原文地址:https://www.cnblogs.com/Jaehwan/p/9691444.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved