如何垂直居中一个浮动元素

16 篇文章 0 订阅
14 篇文章 0 订阅
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    /* 已知宽高进行居中 */
    #known {
      position: relative;
      height: 500px;
      background: palegreen;
    }

    #known p {
      width: 200px;
      height: 200px;
      background: orange;
      position: absolute;
      top: 50%;
      left: 50%;
      /* 二分之一的宽高 */
      margin-left: -100px;
      margin-top: -100px;
    }


    /*  未知宽高进行居中  */
    #unknown {
      position: relative;
      height: 500px;
      background: orchid;
    }

    #unknown p {
      width: 200px;
      height: 200px;
      background: orangered;
      position: absolute;
      margin: auto;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    }

    /* 图片的居中 */
    #images {
      line-height: 800px;
      text-align: center;
    }

    img {
      vertical-align: middle;
    }
  </style>
</head>

<body>
  <!--  已知宽高进行居中  -->
  <!-- <div id="known">
    <p></p>
  </div> -->

  <!-- 未知宽高进行居中 -->
  <!-- <div id="unknown">
    <p></p>
  </div> -->

  <!-- 图片的居中 -->
  <div id="images">
    <img src="../img/8.jpg" alt="">
  </div>
</body>

</html>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HTML 中实现文本的垂直居中和水平居中最常见的方法有几种: ### 水平居中 #### 使用 Flexbox ```html <div class="container"> <div class="text">内容</div> </div> <style> .container { display: flex; justify-content: center; /* 或者使用 'center' */ } .text { /* 可以添加一些样式,如字体大小、颜色等 */ } ``` #### 使用 CSS Grid ```html <div class="grid-container"> <div class="text">内容</div> </div> <style> .grid-container { display: grid; place-items: center; /* 同样可以使用 'center' */ } .text { /* 样式同上 */ } ``` #### 使用 margin 属性调整元素位置 这种方法比较原始,适用于简单的布局。 ```html <div style="position: relative;"> <div style="display: inline-block; position: absolute; top: calc(50% - 1em); left: calc(50% - 1em);"> 内容 </div> </div> ``` ### 垂直居中 #### 使用 Flexbox ```html <div class="container"> <div class="text">内容</div> </div> <style> .container { display: flex; align-items: center; } .text { /* 样式... */ } ``` #### 使用 CSS Grid ```html <div class="grid-container"> <div class="text">内容</div> </div> <style> .grid-container { display: grid; height: 100%; /* 或其他需要的高度 */ align-items: center; } .text { /* 样式... */ } ``` #### 自动对齐元素高度 在某些特定场景下,如果元素的内容固定高度且容器足够大,通常不需要额外的垂直居中代码,例如: ```html <div>内容</div> ``` 在这种情况下,由于 div 的默认内边距和边界可能会导致轻微的上下浮动,可以通过设置 `margin-bottom` 到 `-auto` 来模拟垂直居中效果。 ```css .text { margin-bottom: -auto; } ``` --- ### 相关问题: 1. **如何让表格内的文本垂直和水平居中?** 2. **使用Flexbox和CSS Grid的区别是什么,在哪种情况更适合垂直居中?** 3. **为什么有些开发者更偏好于使用Flexbox而不是CSS Grid来处理布局?**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值