【问题标题】:Vertically align an inline-block in a div with a fixed height垂直对齐具有固定高度的 div 中的内联块
【发布时间】:2015-06-01 03:14:56
【问题描述】:

CodePen

我想垂直和水平对齐,容器的高度和宽度将根据其他外部因素固定。

我该怎么做?

我尝试过使用 flex

display: flex;
justify-content: center;
flex-direction: column;

但它摆脱了我的水平对齐方式

【问题讨论】:

标签: html css vertical-alignment


【解决方案1】:

其实有multipleways实现垂直对齐,这里有一个:

div {
  width: 300px;
  height: 150px;
  background-color: #ddd;
  text-align: center;
  font-size: 0;
}

div::before {
  content: "";
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

a {
  width: 100px;
  height:50px;
  background-color: #ff0000;
  display: inline-block;
  vertical-align: middle;  
  font-size: 16px
}
<div>
  <a href="#">Some Text</a>
</div>

【讨论】:

  • 谢谢!就在您回复之前,我使用 position:relative; 找到了答案和位置:绝对;
  • @Pontiacks 不客气。是的,正如我所提到的,有几种方法,但我假设您希望将元素保持为正常流动的 inline-block 元素,这在问题的标题中明确说明。
【解决方案2】:

找到了解决办法!

在 div 父级上:

position:relative;

关于孩子:

position: absolute;
top: 50%;
left: 50%;
margin-left: -half_its_width;
margin-top: -half_his_height;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-01
    • 2015-05-26
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多