如何在中间(垂直)对齐文本

时间:2015-12-17 23:53:44

标签: html css alignment vertical-alignment

我现在正在努力工作这几个小时仍然无法找到解决方案。我已经制作了这个漂亮的网格,可以根据文本长度和浏览器调整进行调整。现在的问题是,我无法将文字放在框中间。

我已经尝试了所有的东西..为了达到这个目的,我使用了几个属性,但没有任何效果。

text-align: center;
vertical-align: middle;
line-height: "same as div";

css代码:

.parent {
  text-align:center;
  margin:0px;
  width:100%;
  padding:0px;
  font-size:18px;
  color:#000;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
      justify-content: space-between;
}

.child {
  padding:18px 25px;
  background: rgba(0, 0, 0, .5);
  list-style-type:none;
  width:inherit;
  margin:5px;

}

3 个答案:

答案 0 :(得分:5)

这是你想要的吗?

.parent {
    text-align:center;
    margin:0px;
    width:100%;
    padding:0px;
    font-size:18px;
    color:#000;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    vertical-align: middle;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    -ms-flex-pack: justify;
    justify-content: space-between;

}

.child {
    position: relative;
    background: rgba(0, 0, 0, .5);
    padding:10px;
    list-style-type:none;
    width:inherit;
    align-items: center;
    justify-content: center;
    height:inherit;
    display: inline-flex;
    vertical-align: middle;
    margin:5px;
}
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="parent">
    <div class="child"><span>sometext</span></div>
    <div class="child">somemoretext somemoretext</div>
    <div class="child">sometext</div>
    <div class="child">sometext</div>
</div>
<div class="parent">
    <div class="child">somemoretext somemoretext somemoretext somemoretext</div>
    <div class="child">sometext</div>
</div>
</body>
</html>

这是使用flex作为ur jsfiddle完成的。你可以通过“父显示表和垂直对齐中间”和“子显示表格单元格和面板中间”删除你的flex样式更容易。

答案 1 :(得分:2)

如果您不关心具有多行文字的div将其高度调整为实际文字内容,请在height:100%元素上使用child

如果您需要所有内容保持相同的高度,请添加

// Use any fixed value
    line-height: 50px;
    height: 50px;

如果您需要在调整窗口大小时更改固定高度(以像素为单位),只需使用javascript更改CSS规则(如果使用此方法首先阅读this,则在窗口更改时不要减慢客户端的速度)。

答案 2 :(得分:1)

你试过了吗?

保证金:0自动;

相关问题