簡體   English   中英

如何在Flexbox中居中放置內容

[英]How to center content in a flexbox

我的項目出現問題,內容在Flexbox中未垂直對齊。 我們有一個響應迅速的頁面,需要通過%將居中的Flexbox中的所有項目居中。 在下面的示例中,我們將像素高度設置為固定,以便您可以使用它。

我已經嘗試了數小時的多種方法。

body{
  margin:0px auto;

}
/* top bar navigation */
.topBoxNav {
  background:red;
  padding: 0;
  list-style: none;
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  width: 100%;
  height: 50px;
  color: white;
  font-weight: bold;
  font-family: 'League Gothic';
  font-size: 1.5em;
  text-align: center;
}

.topBoxNav li {
  box-sizing: border-box;
  border: 1px solid white;
  width: 100%;
  height: 100%;
}

.topBoxNav a {
  text-decoration: none;
  color: white;
}

HTML:

<nav class="" alt="top Nav">
  <ul class="topBoxNav">
    <li><a href="">Box1</a></li>
    <li><a href="">Box2</a></li>
    <li><a href="">Box3</a></li>
  </ul>     
</nav>

例:

http://codepen.io/anon/pen/iwDdy

首先,認識到display: flex屬性是您的ul ,而不是您的li元素,因此您在這里有兩個選擇:

1)給您的li元素display: flex並添加align-items: center ,並justify-content: center

您將獲得如下內容:

.topBoxNav li {
  box-sizing: border-box;
  border: 1px solid white;
  width: 100%;
  height: 100%;

  display: flex;

  align-items center
  -moz-align-items center
  -ms-flex-align center
  -webkit-align-items center

  justify-content center
  -moz-justify-content center
  -ms-flex-pack center
  -webkit-justify-content center
}

2)給您的li元素line-height等於height ,在這種情況下為50pxvertical-align: middle

您將擁有以下內容:

.topBoxNav li {
  box-sizing: border-box;
  border: 1px solid white;
  width: 100%;
  height: 100%;
  align-items: center;
  -webkit-align-items: center;
  vertical-align: middle;
  line-height: 50px;
}

兩種方式都可以工作:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM