使用CSS定位可以指定元素的定位方式以及元素在页面上的位置。
术语“CSS定位”通常是指使用position属性来指定元素的定位方式。例如,您可以指定是否希望元素相对于其在页面中的自然位置、绝对位置(从正常流中取出)、固定位置等位置。文章源自你的网络首码项目网-https://www.youranweb.com/270.html
相对定位
要在CSS中执行相对定位,请使用后跟所需的从顶部、右侧、底部或左侧偏移。position:relative;文章源自你的网络首码项目网-https://www.youranweb.com/270.html
<!DOCTYPE html> <title>Example</title> <style> div { position: relative; left: 50px; background-color: gold; width: 90px; } </style> <p>以下是内容的正常流程...</p> <div> 此 div 具有相对位置。 </div> <p>...这里有更多内容...</p>
本示例将元素从原来的位置左侧偏移80像素。如果我们指定了top,它将出现在它原来的位置下方80像素。请务必注意,其他元素不受此元素偏移量的影响。因此,可能会发生重叠。文章源自你的网络首码项目网-https://www.youranweb.com/270.html
绝对定位
若要在CSS中执行绝对定位,请再次使用位置属性。只是,这次您使用use后跟所需的偏移量。position:absolute;文章源自你的网络首码项目网-https://www.youranweb.com/270.html
<!DOCTYPE html> <title>Example</title> <style> div { position: absolute; top: 100px; left: 60px; background-color: gold; width: 90px; padding: 20px; } </style> <div> 该div绝对位于距其包含块顶部100像素和左侧60像素的位置。 </div>
固定定位
固定定位允许您将元素的位置固定到页面上的特定位置-无论滚动如何。文章源自你的网络首码项目网-https://www.youranweb.com/270.html
<!DOCTYPE html> <title>Example</title> <style> .absolute { position: absolute; top: 500px; left: 60px; height: 2000px; background-color: limegreen; } .fixed { position: fixed; top: 10px; left: 10px; background-color: gold; width: 90px; padding: 20px; } </style> <div class="absolute"> 这个高div绝对位于距其包含块的顶部500像素和左侧60像素处。 </div> <div class="fixed"> 该div使用的固定位置为距其包含块顶部100像素和距其左侧60像素。当此页面滚动时,此框将保持在固定位置,不会与页面的其他部分一起滚动。继续-滚动! </div>
文章源自你的网络首码项目网-https://www.youranweb.com/270.html 文章源自你的网络首码项目网-https://www.youranweb.com/270.html

评论