CSS样式基础
CSS定位
重要程度:7 分
<div>
<h2>CSS定位概述</h2>
<p>CSS定位用于控制元素在页面上的位置。主要的定位方式有:</p>
<ul>
<li>静态定位(static):默认值,按照HTML文档流自然布局。</li>
<li>相对定位(relative):相对于自身正常位置偏移,原有位置保留空间。</li>
<li>绝对定位(absolute):相对于最近的已定位祖先元素,如果没有,则相对于初始包含块(通常是浏览器窗口)。绝对定位后原有位置不保留空间。</li>
<li>固定定位(fixed):相对于浏览器窗口,不会随滚动条滚动而移动。</li>
<li>粘性定位(sticky):基于用户滚动位置进行定位,是一种相对定位和固定定位的混合。</li>
</ul>
<h3>示例1:相对定位</h3>
<p>给一个div设置相对定位,并移动它。</p>
<div style="width: 100px; height: 100px; background-color: lightblue; position: relative; top: 20px; left: 30px;">
这是一个相对定位的div。
</div>
<h3>示例2:绝对定位</h3>
<p>给一个div设置绝对定位,并放置在页面右下角。</p>
<div style="width: 100px; height: 100px; background-color: lightgreen; position: absolute; bottom: 0; right: 0;">
这是一个绝对定位的div。
</div>
<h3>示例3:固定定位</h3>
<p>给一个div设置固定定位,并使其始终位于屏幕中心。</p>
<div style="width: 100px; height: 100px; background-color: lightcoral; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);">
这是一个固定定位的div。
</div>
<h3>示例4:粘性定位</h3>
<p>给一个div设置粘性定位,当滚动到一定位置时固定在顶部。</p>
<div style="width: 100%; height: 2000px; background-color: #f0f0f0;">
滚动页面...
</div>
<div style="width: 100px; height: 50px; background-color: lightgoldenrodyellow; position: -webkit-sticky; position: sticky; top: 0;">
这是一个粘性定位的div。
</div>
</div>