博主信息
博文 6
粉丝 0
评论 0
访问量 6079
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
CSS盒模型理解与盒子垂直水平居中
遇见
原创
1348人浏览过

一、盒模型

1.什么是盒模型:HTML中,所有的元素都可以看成是盒模型

2.盒模型从内到外,依次为:

2.1 内容区;
2.2 内边距(padding)
2.3 边框(border);
2.4 外边距(margin);

(注意:IE浏览器内容区宽度包括了内边距和边框的宽度);

div盒子模型图:

二、div盒子水平垂直居中

1.position绝对定位:分为2种,一种是fixed,另外一种是absolute;

position:fixed这种表示相对浏览器进行绝对定位,div定位后,div脱硫文档流,不再随浏览器页面滚动;
position:absolute这种是相对父级元素进行绝对定位,所以要求父级元素进行相对定位position:relative,如果父级元素没有进行相对定位,那元素会一直往上寻找进行了相对定位的父元素;

fixed定位后水平垂直居中代码:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>fixed绝对定位</title>
  7. <style type="text/css">
  8. /* 浏览器默认外边距8像素,全部初始化0 */
  9. * {
  10. padding: 0;
  11. margin: 0;
  12. }
  13. .box {
  14. width: 400px;
  15. height: 400px;
  16. background: lightgreen;
  17. position: fixed;
  18. left: 0;
  19. right: 0;
  20. top: 0;
  21. bottom: 0;
  22. margin: auto;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <div class="box"></div>
  28. </body>
  29. </html>

预览样式

absolute定位后水平垂直居中代码:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>absolute水平垂直居中</title>
  7. <style type="text/css">
  8. /* 浏览器默认外边距8像素,全部初始化0 */
  9. * {
  10. padding: 0;
  11. margin: 0;
  12. }
  13. .box {
  14. width: 400px;
  15. height: 400px;
  16. background: lightgreen;
  17. /* 使用absolute时,父元素必须进行相对定位 */
  18. position: relative;
  19. }
  20. .box .boxitem {
  21. width: 300px;
  22. height: 300px;
  23. background: lightsalmon;
  24. /* 下面2行是文本在块元素中水平垂直居中 */
  25. text-align: center;
  26. line-height: 300px;
  27. /* 盒子在父容易中水平垂直居中样式 */
  28. position: absolute;
  29. left: 0;
  30. right: 0;
  31. top: 0;
  32. bottom: 0;
  33. margin: auto;
  34. /* 盒子宽高固定时,也可以这样来进行水平垂直居中
  35. position: absolute;
  36. top: 50%;
  37. left: 50%;
  38. margin-top: -150px;
  39. margin-left: -150px; */
  40. }
  41. </style>
  42. </head>
  43. <body>
  44. <div class="box">
  45. <div class="boxitem">盒子在父容器中水平垂直居中</div>
  46. </div>
  47. </body>
  48. </html>

预览样式:

批改老师:WJWJ

批改状态:合格

老师批语:总得来说写的不错,盒模型属性和元素大小相对简单了点!
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系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+教程免费学