博客列表 >CSS盒模型理解与盒子垂直水平居中

CSS盒模型理解与盒子垂直水平居中

遇见
遇见原创
2020年06月18日 16:18:161031浏览

一、盒模型

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>

预览样式:

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议