如何对齐两个<a> to the center using flexbox?

时间:2017-02-06 05:10:58

标签: css flexbox

Below are my html and css code.

.tab {
  display: flex;
  self-align: center;
  align-items: center;
  margin: auto;
  width: 100%;
  border: 1px solid red;
}

.section-title {
  display: flex;
  margin: 5px;
}
.label {
  display: flex;
  padding: 10px;
}
.label-a {
  color: white;
  background-color: green;
}
.label-b {
  color: white;
  background-color: orange;
}
<div class=tab>
  <a class=section-title>
    <div class="label label-a">Tab a</div>
  </a>
  <a class=section-title>
    <div class="label label-b">Tab b</div>
  </a>
</div>

Currently it gives the following result: enter image description here

我的目标是让绿色和橙色框移动到红色边框的中心,如下所示:

enter image description here

我尝试了一些例如:

1)使用margin: auto

2)确保.tab宽度为100%。

3).section-title.labeldisplay属性中使用flexbox

为什么对齐不能像我预期的那样工作?是因为a不是块元素吗?

2 个答案:

答案 0 :(得分:1)

您需要将justify-content:center添加到.tab类:

.tab {
   display: flex;
   self-align: center;
   align-items: center;
   margin: auto;
   width: 100%;
   justify-content: center;
   border: 1px solid red;
}

答案 1 :(得分:0)

为什么不简单地text-align: center

&#13;
&#13;
.tab {
  text-align: center;
  width: 100%;
  border: 1px solid red;
}

.section-title {
  margin: 5px;
}
.label {
  padding: 10px;
  display: inline-block;
}
.label-a {
  color: white;
  background-color: green;
}
.label-b {
  color: white;
  background-color: orange;
}
&#13;
<div class=tab>
  <a class=section-title>
    <div class="label label-a">Tab a</div>
  </a>
  <a class=section-title>
    <div class="label label-b">Tab b</div>
  </a>
</div>
&#13;
&#13;
&#13;