博主信息
博文 6
粉丝 0
评论 0
访问量 3958
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
传统定位和flex定位
深海
原创
761人浏览过
  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>

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学