我试图垂直居中我的标签内容,但当我添加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>


当前回答

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

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

其他回答

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

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

不需要父样式。

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

你可以使用CSS(你的元素显示:inline-grid + grid-auto-flow: row;)网格和Flex Box(父元素显示:Flex;),

参见下面的片段

# leftFrame { 显示:flex; 身高:100 vh; 宽度:100%; } 标签# { 显示:inline-grid; grid-auto-flow:行; grid-gap: 24 px; justify-items:中心; 保证金:汽车; } html,身体{ 保证金:0; 填充:0; } < div > < div id = leftFrame > < div id = >标签 首先< div > < / div > < div >第二< / div > < / div > < / div > < / div >

下面是获得理想结果的Flex-box方法

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Flex-box approach</title> <style> .tabs{ display: -webkit-flex; display: flex; width: 500px; height: 250px; background-color: grey; margin: 0 auto; } .f{ width: 200px; height: 200px; margin: 20px; background-color: yellow; margin: 0 auto; display: inline; /*for vertically aligning */ top: 9%; /*for vertically aligning */ position: relative; /*for vertically aligning */ } </style> </head> <body> <div class="tabs"> <div class="f">first</div> <div class="f">second</div> </div> </body> </html>

CSS网格:位置项

最后,我们有place-items: center for CSS Grid以使它更容易。

HTML

<div class="parent">
  <div class="to-center"></div>
</div>

CSS

.parent {
  display: grid;
  place-items: center;
}

输出:

超文本标记语言 身体{ 高度:100%; } .container { 显示:网格; 名:中心; 高度:100%; } .center { 背景:# 5 f85db; 颜色:# fff; 粗细:大胆的; 字体类型:大河马字体; 填充:10 px; } < div class = "容器" > <div class="center" contenteditable>我总是超级集中在我的父母</div> < / div >

需要遵循以下新的和简单的解决方案: .centered-class { 对齐项目:中心; 显示:flex; justify-content:中心; 宽度:100大众; 身高:100 vh; } < div class = " centered-class”> 我在垂直和水平的中心。 < / div >