首页 > 解决方案 > 在 div 中垂直对齐项目

问题描述

我有一个 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>

任何帮助表示赞赏。

标签: htmlcss

解决方案


试试这个:

.actions容器需要使flex两个actions容器均匀间隔并排。

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

容器内的a标签action需要是 100% 的高度/宽度,以便它们填满整个.action容器。但是,要使文本垂直和水平居中,您可以使用 flex 以便您可以使用justify-content: centerand align-items:center- 这使得其中的内容水平居中(justify-content)和垂直居中(align-items)。

.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>


推荐阅读