html - div 中的居中文本和 calc() 疑惑

标签 html css

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

<!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() 的情况下将元素 #center 置于 div 中?

最佳答案

在您的结构中,display:tabledisplay:table-cell 将不起作用,因为您在 .item 中使用了绝对位置。

在所有浏览器都支持的 #center 中使用下面的 css。

#center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  //top: calc(50% - 2em);
  //right: calc(50% - 2em);
}

示例:https://jsfiddle.net/vzk5arxe/2/

关于html - div 中的居中文本和 calc() 疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37044105/

相关文章:

javascript - 使用 jquery UI 可调整大小的分屏 div

javascript - 移动元素时如何更改悬停状态?

php - 使用 session 显示/隐藏 div (php)

javascript - 使用 Chrome DevTools 将鼠标悬停在自定义元素上时,自定义元素不会被标记

javascript - HTML 控件同时同步(相同或不同的浏览器)

javascript - 按钮在 jQuery 中不起作用

html - 背景 SVG 不会在 Bootstrap div 列中缩放

html - 如何在占位符属性中设置单个单词的样式

javascript - 用 next 和 prev 突出显示 P 标签

html - 在 Img 上叠加 Figcaption