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>元素居中的两种方法</title>
  8. <style>
  9. .box {
  10. width: 15em;
  11. height: 15em;
  12. background-color: crimson;
  13. position: relative;
  14. }
  15. .box .sun {
  16. width: 5em;
  17. height: 5em;
  18. background-color: darkblue;
  19. position: absolute; /**绝对定位*/
  20. top: 0;
  21. left: 0;
  22. right: 0;
  23. bottom: 0; /**top left right bottom 等于0让盒子居中*/
  24. margin: auto; /*这一行才做了sun 元素再box中的居中效果,没有的话无效果*/
  25. }
  26. .box1 {
  27. width: 15em;
  28. height: 15em;
  29. background-color: darkorange;
  30. display: flex;
  31. justify-content: center;
  32. align-items: center;
  33. /** display: flex;justify-content: center; align-items: center; 完成了利用flex居中效果*/
  34. }
  35. .box1 .sun1 {
  36. width: 5em;
  37. height: 5em;
  38. background-color: darkslateblue;
  39. }
  40. </style>
  41. </head>
  42. <body>
  43. <h2>传统居中</h2>
  44. <div class="box">
  45. <div class="sun"></div>
  46. </div>
  47. <h2>flex居中</h2>
  48. <div class="box1">
  49. <div class="sun1"></div>
  50. </div>
  51. </body>
  52. </html>

更多相关文章

  1. IDEA激活码2020 最新激活码2021.3.2 永久更新 亲测有效
  2. box-sizing功能。相对定位与绝对定位。绝对定位:块级居中。
  3. 0323作业
  4. 0323作业-CSS盒模型、CSS相对定位和绝对定位及块元素垂直居中
  5. 定位属性position 的介绍
  6. 商品详情平面设计,图片文字的镜像处理
  7. web前端编程语言有哪些?
  8. 用函数公式制作旋风图,75.42%的人没想到!
  9. 机器学习开篇小菜

随机推荐

  1. 关于XML文档类型的详细介绍
  2. 在IE下字符串与XML转换产生BUG的解决方案
  3. XML DOM对象方法的实例解析
  4. 调用API生成RSS资源文件的实例详解
  5. XML编码基础实例详解
  6. 手动生成评论RSS的代码实例
  7. 如何实现XML文档和JTree之间转换
  8. DTD和XSD在XML中的区别以及应用详解
  9. 配置struts.xml的实例详解
  10. 关于JSON和XML优缺点的具体介绍