在div中垂直对齐项目

时间:2020-10-22 00:42:35

标签: html css

我有一个div,里面有一个锚点,我希望该锚点占据div的整个宽度,但是,我希望将锚点的文本放在div的中心,这对我来说不起作用。我已经尝试过此代码:

  .actions {
    display: -webkit-flex;
    display: flex;
  }
  .action {
    background: #ef5b2b;
    -webkit-flex: 1;
    -ms-flex: 1;
    flex: 1;
    margin: 5px;
    text-align: center;
    height: 100px; 
    position: relative;
  }

  .action a {
      display: inline-block;
      height: 100%;
      width: 100%;
      vertical-align: middle;
}
<div class="actions">
  <div class="action-left action">
    <a href="#" style="color: white">Hello 1</a>
  </div>

  <div class="action-right action">
    <a href="#" style="color: white">Hello 2</a>
  </div>
</div>

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

尝试一下:

.actions容器需要为flex,以便两个actions容器并排均匀分布。

每个.action容器将容纳两个锚定容器(高度和宽度为100%)。因此,.action容器本身仅需100%的宽度/高度。

a容器中的action标签必须为100%的高度/宽度,以便它们填充整个.action容器。但是,要使文本在水平和垂直方向上居中,可以使用flex,以便可以使用justify-content: centeralign-items:center-使文本中的内容在水平(对齐内容)和垂直(对齐-项)。

.actions {
    width: 100%;
    display: flex;
  }
  .action {
    flex: 1;
    position: relative;
    width: 100%;
    height: 100px; 
    margin: 5px;
    background: #ef5b2b;
  }
  
.action a{
  height:100%;
  width:100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="actions">
  <div class="action-left action">
    <a href="#" style="color: white">Hello 1</a>
  </div>

  <div class="action-right action">
    <a href="#" style="color: white">Hello 2</a>
  </div>
</div>

相关问题