微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – div中的文本和calc()怀疑

如何将文本(p)在div(.item)内垂直和水平居中?

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <Meta charset="utf-8" />
    <title></title>
    <style type="text/css">
        .wrapper {
            width: auto;
            height: 10em;
            background-color: red;
            position: relative;
        }
        .item {
            width: 4em;
            height: 4em;
            background-color: black;
            position: absolute;
            display: inline-block;
            color: white;
        }
        .item p {
            text-align: center;
            vertical-align: middle;
        }
        #top-right {
            right: 0em;
        }
        #center {
            top: calc(50% - 2em);
            right: calc(50% - 2em);
        }
        #bottom-left {
            bottom: 0em;
            left: 0em;
        }
        #bottom-right {
            right: 0em;
            bottom: 0em;
        }
    </style>
</head>
<body>
    <header></header>
    <main>
        <div class="wrapper">
            <div class="item" id="top-left"><p>Top Left</p></div>
            <div class="item" id="top-right"><p>Top Right</p></div>
            <div class="item" id="center"><p>Center</p></div>
            <div class="item" id="bottom-left"><p>Bottom Left</p></div>
            <div class="item" id="bottom-right"><p>Bottom Right</p></div>
        </div>
    </main>
    <footer></footer>
</body>
</html>

可以使用calc(因为我读到某些浏览器不支持功能)?或者还有另一种方法可以在没有calc()的div中将元素#center居中?

解决方法

您可以使用display:flex来实现.我已将以下属性添加到您的.item中

display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;

更新的代码段:

.wrapper {
  width: auto;
  height: 10em;
  background-color: red;
  position: relative;
}
.item {
  width: 4em;
  height: 4em;
  background-color: black;
  position: absolute;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}
#top-right {
  right: 0em;
}
#center {
  top: calc(50% - 2em);
  right: calc(50% - 2em);
}
#bottom-left {
  bottom: 0em;
  left: 0em;
}
#bottom-right {
  right: 0em;
  bottom: 0em;
}
<header></header>
<main>
  <div class="wrapper">
    <div class="item" id="top-left">
      <p>Top Left</p>
    </div>
    <div class="item" id="top-right">
      <p>Top Right</p>
    </div>
    <div class="item" id="center">
      <p>Center</p>
    </div>
    <div class="item" id="bottom-left">
      <p>Bottom Left</p>
    </div>
    <div class="item" id="bottom-right">
      <p>Bottom Right</p>
    </div>
  </div>
</main>
<footer></footer>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐