鱼C论坛

 找回密码
 立即注册
查看: 2818|回复: 2

[已解决]父级div高度自适应,如何使其中内容垂直居中

[复制链接]
发表于 2021-11-8 10:10:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
提问 因为编写的网页要实现不同屏幕自适应大小 所以div模块的大小都用百分比设置了 这样子情况下div块的大小高度都是未知的 我想实现将其中的文字居中显示 之前使用的是line-height设置高度加上具体大小px 但是现在父级元素的高度未知 在这种情况下 想实现块级元素里面的文字居中显示该如何实现呢?
            width: 10%;
            height: 100%;
            display: inline-block;
            text-decoration: none;
            color: white;
            text-align: center;
            line-height: 50px;
            font-size: 100%;
            background-color: black;
我的代码如下
最佳答案
2021-11-8 11:21:56
<!DOCTYPE html>
<html>
<head>
  <title>text</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }

    #box{
      margin: 100px auto;
      height: 400px;
      width: 1200px;
      border: 1px solid aqua;
    }

    .inbox{
      display: inline-block;
      width: 10%;
      height: 100%;
      text-decoration: none;
      color: white;
      font-size: 100%;
      background-color: black;
      text-align: center;
    }

    .text{
      /* 使用定位和位移实现垂直居中 */
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }

  </style>
</head>
<body>
  <!-- 父元素 -->
  <div id="box"> 
    <!-- 子元素 -->
    <div class="inbox">
      <!-- 被垂直居中的部分 -->
      <p class="text">测试文本</p>
    </div>
  </div>
</body>
</html>

大概就这样,还是有挺多方法的,我比较喜欢用上面这种
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-11-8 11:15:35 | 显示全部楼层
删除条目
line-height 和 text-align

修改条目
display: inline-flex;

增加条目
align-items: center;
justify-content: center;
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-11-8 11:21:56 | 显示全部楼层    本楼为最佳答案   
<!DOCTYPE html>
<html>
<head>
  <title>text</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }

    #box{
      margin: 100px auto;
      height: 400px;
      width: 1200px;
      border: 1px solid aqua;
    }

    .inbox{
      display: inline-block;
      width: 10%;
      height: 100%;
      text-decoration: none;
      color: white;
      font-size: 100%;
      background-color: black;
      text-align: center;
    }

    .text{
      /* 使用定位和位移实现垂直居中 */
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }

  </style>
</head>
<body>
  <!-- 父元素 -->
  <div id="box"> 
    <!-- 子元素 -->
    <div class="inbox">
      <!-- 被垂直居中的部分 -->
      <p class="text">测试文本</p>
    </div>
  </div>
</body>
</html>

大概就这样,还是有挺多方法的,我比较喜欢用上面这种
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-27 06:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表