如何在 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:table
和 display: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);
}
关于html - div 中的居中文本和 calc() 疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37044105/