我试图垂直居中我的标签内容,但当我添加CSS样式display:inline-flex时,水平文本对齐消失了。

我怎么能使文本对齐x和y为我的每个制表?

* { box-sizing: border-box; } #leftFrame { background-color: green; position: absolute; left: 0; right: 60%; top: 0; bottom: 0; } #leftFrame #tabs { background-color: red; position: absolute; top: 0; left: 0; right: 0; height: 25%; } #leftFrame #tabs div { border: 2px solid black; position: static; float: left; width: 50%; height: 100%; text-align: center; display: inline-flex; align-items: center; } <div id=leftFrame> <div id=tabs> <div>first</div> <div>second</div> </div> </div>


当前回答

如果你喜欢它没有flexbox,网格,表格或垂直对齐:中间;

你可以:

HTML

<div class="box">
    <h2 class="box__label">square</h2>
</div>

CSS

.box {
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    text-align: center;
    border: 1px solid black;
}

.box__label {
    box-sizing: border-box;
    display: inline-block;
    transform: translateY(50%);
    text-align: center;
    border: 1px solid black;
}

其他回答

只要让上下左右都为0。

<html>
<head>
<style>
<div> 
{
position: absolute;
margin: auto;
background-color: lightblue;
width: 100px;
height :100px;
padding: 25px;
top :0;
right :0;
bottom:0;
left:0;
}


</style>
</head>
<body>

<div> I am in the middle</div>

</body>
</html>

如果它只是关于文本对齐,它很简单。就用这个吧:

vertical-align: middle; /* vertical centering*/
text-align: center; /* horizontal centering*/

不需要父样式。

在某些情况下,当父类有一些样式属性时,它可能会影响子类,这将无法正常工作。

对我来说,最简单和最干净的解决方案是使用CSS3属性“transform”:

.container { 位置:相对; } .container a { 位置:绝对的; 上图:50%; 变换:翻译(0 -50%); } < div class = "容器" > <a href="#">Hello world!< / > < / div >

下面是如何使用两个简单的flexbox属性在两个轴上居中n个div:

设置容器的高度:在这里,主体被设置为至少100个视口高度。 对齐项目:中心;如果弯曲方向是行,将垂直中心块,否则水平,如果弯曲方向是列 justify-content:空间;将分配自由空间垂直如果弯曲方向是行或水平如果弯曲方向是列围绕div元素

身体{ 最小高度:100 vh; 显示:flex; 对齐项目:中心; justify-content:空间; } < div > foo < / div > 酒吧< div > < / div >

网格css方法

#包装{ 位置:绝对的; 上图:0; 底部:0; 右:0; 左:0; 显示:网格; Grid-template-columns: repeat(3,1fr); Grid-template-rows: repeat(3,1fr); } .main { background - color: # 444; } < div id = "包装" > < div class = "盒子" > < / div > < div class = "盒子" > < / div > < div class = "盒子" > < / div > < div class = "盒子" > < / div > <div class="box main"></div> < / div >