CSS长度单位:px、em、rem的理解 - 附带案例

x33g5p2x  于2022-02-24 转载在 CSS3  
字(2.0k)|赞(0)|评价(0)|浏览(424)

长度单位

概念

长度单位px:相对于屏幕em:当前节点font-size 1em的标准取父节点的font-size长度,而当前节点的其他属性长度1em以当前节点的font-size长度为标准rem:1rem的长度为根节点的font-size长度为标准,【不像em那样涉及到父节点的标准】

示例讲解

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. <script src="G:\VsCode\开源\jquery-3.5.1\jquery-3.5.1.min.js"></script>
  9. <style>
  10. html {
  11. font-size: 30px;
  12. color: rgb(236, 96, 96);
  13. text-align: center;
  14. }
  15. html div {
  16. margin: 0 auto;
  17. }
  18. button {
  19. font-size: 40px;
  20. }
  21. #box1 {
  22. width: 300px;
  23. height: 300px;
  24. font-size: 60px;
  25. background-color: gold;
  26. }
  27. #box1 p {
  28. font-size: 90px;
  29. }
  30. /* 当前节点的font-size取其父节点body的font-size即30px 所以这里font-size为60px ==> 当前节点的其他属性以当前节点的font-size的1em标准故 width=10em=600px height=10em=600px */
  31. #box2 {
  32. width: 10em;
  33. height: 10em;
  34. font-size: 2em;
  35. background-color: black;
  36. }
  37. /**父节点box2的font-size为60px, 故此节点的font-size: 180px*/
  38. #box2 p {
  39. font-size: 3em;
  40. }
  41. /* 所有长度单位1rem的标准都取根节点<html>的font-size为1rem标准,故2rem=60px 10rem=300px */
  42. #box3 {
  43. width: 10rem;
  44. height: 10rem;
  45. font-size: 2rem;
  46. background-color: aquamarine;
  47. }
  48. /* 所有长度单位1rem的标准都取根节点<html>的font-size为1rem标准,故2rem=60px*/
  49. #box3 p {
  50. font-size: 2rem;
  51. }
  52. </style>
  53. </head>
  54. <body>
  55. <button id="btn0" >html根节点默认60px</button>
  56. <button id="btn1">html根节点设为40px</button>
  57. <button id="btn2">html根节点设为50px</button>
  58. <div id="box1">
  59. <p>你好1</p>
  60. </div>
  61. <div id="box2">
  62. <p>你好2</p>
  63. </div>
  64. <div id="box3">
  65. <p>你好3</p>
  66. </div>
  67. </body>
  68. <script>
  69. $(function () {
  70. $("#btn0").click(() => {
  71. $("html").css("font-size","60px");
  72. });
  73. $("#btn1").click(() => {
  74. $("html").css("font-size","40px");
  75. });
  76. $("#btn2").click(() => {
  77. $("html").css("font-size","50px");
  78. });
  79. });
  80. </script>
  81. </html>

相关文章