CSS定位(相对定位,固定定位,绝对定位)

刺骨的言语ヽ痛彻心扉 2023-01-11 09:15 300阅读 0赞

在CSS中,可以使用position属性来定位元素。position 属性规定元素的定位类型。

属性值:

  • absolute:生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。
  • fixed:生成固定定位的元素,相对于浏览器窗口进行定位。元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。
  • relative:生成相对定位的元素,相对于其正常位置进行定位。因此,“left:20” 会向元素的 LEFT 位置添加 20 像素。
  • static:默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。

相对定位:

相对于其正常位置进行定位。(可以用来对标签的位置进行微调)

  1. <html>
  2. <head>
  3. <title>相对定位</title>
  4. <meta charset="utf-8">
  5. <style type="text/css">
  6. body{
  7. height: 2000px;
  8. }
  9. #span2{
  10. position: relative;/*设置定位方式为相对定位*/
  11. top: 20px;
  12. left: 14px;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <span id="span1">这是一</span>
  18. <span id="span2">这是二</span>
  19. <span id="span3">这是三</span>
  20. </body>
  21. </html>

固定定位

始终相对于浏览器窗口进行定位。

  1. <html>
  2. <head>
  3. <title>固定定位</title>
  4. <meta charset="utf-8">
  5. <style type="text/css">
  6. body{
  7. height: 2000px;
  8. }
  9. div{
  10. width: 500px;
  11. height: 300px;
  12. border:solid 2px red;
  13. position: fixed;/*设置定位方式为固定定位*/
  14. bottom:500px 1px ;
  15. }
  16. p{
  17. float: right;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <div>这是一个div盒子</div><br>
  23. <p>这个不会动</p>
  24. </body>
  25. </html>

绝对定位

相对于 static 定位以外的第一个父元素进行定位。

  1. <head>
  2. <title>绝对定位</title>
  3. <meta charset="utf-8">
  4. <style type="text/css">
  5. div{
  6. width: 500px;
  7. height: 400px;
  8. border: solid 2px red;
  9. /*给div设置相对定位,使得div作为section的参照物进行绝对定位*/
  10. position: relative;
  11. }
  12. section{
  13. width: 50px;
  14. height: 40px;
  15. background-color: yellow;
  16. position: absolute;/*设置定位方式为绝对定位*/
  17. /*让section始终在div右下角*/
  18. /*让section相对在div右侧距离为0*/
  19. /*让section相对在div低侧距离为0*/
  20. /*绝对定位必须设置参照物,若未设置参照物,则相对于body进行定位*/
  21. right: 0px;
  22. bottom: 0px;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <div>
  28. <section></section>
  29. </div>
  30. </body>

发表评论

表情:
评论列表 (有 0 条评论,300人围观)

还没有评论,来说两句吧...

相关阅读