[关闭]
@xunuo 2021-06-21T02:55:51.000000Z 字数 1471 阅读 1423

如何实现水平、垂直居中

前端



方法一:父元素设置display:flex;
子元素设置margin:auto;
具体代码实现如下:

  1. <div class="flex-container">
  2. <div class="flex-item"></div>
  3. </div>
  4. <style>
  5. .flex-container {display:flex;width:500px;height:500px;background:lightgray;}
  6. .flex-item {margin:auto;width:200px;height:200px;background:darkred;}
  7. </style>

方法二:父元素设置display:flex;
然后再通过弹性盒子属性设置水平和垂直居中:
水平居中:align-items:center;
垂直居中:justify-content:center;
具体实现代码如下:

  1. <div class="parentDiv">
  2. <div class="childDiv">
  3. 这是一段文字
  4. </div>
  5. </div>
  6. <style>
  7. /**这里是设置parentDiv相对于整个页面居中:*/
  8. html,body{
  9. width: 100%;
  10. height: 100%;
  11. display: flex;
  12. align-items: center;
  13. justify-content: center;
  14. }
  15. /**这里是设置childDiv居中*/
  16. .parentDiv {
  17. width: 700px;
  18. height: 500px;
  19. display: flex;
  20. align-items: center;
  21. justify-content: center;
  22. border: 1px solid #FF0000;
  23. }
  24. /**childDiv的设置,在里面设置了文字居中*/
  25. .childDiv {
  26. border: 1px solid #000000;
  27. width: 500px;
  28. height: 100px;
  29. /*文字设置*/
  30. font-size: 36px;
  31. text-align: center;
  32. line-height: 100px;
  33. }
  34. </style>
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注