首页 > 解决方案 > 保持文本在容器内垂直居中

问题描述

我试图在 li 元素中保留一段呈现的文本,但我不知道该怎么做。我查找了说使用 line-height、vertical-align 和其他的教程,但是我无法让它们中的任何一个工作。

我试图在 li 元素中保持“Shop”文本垂直和水平对齐。我怎样才能做到这一点?

ul {
  position: absolute;
  padding-left: 0px;
  width: 100%;
  height: 15%;
  top: 1%;
  list-style-type: none;
  background-color: #f8d7d7;
}

li {
  float: left;
  width: 10%;
  height: 100%;
  background-color: green;
  text-align: center;
  font-size: 2.5vw;
}
<ul>
  <li>
    Shop
  </li>
</ul>

这是一个小提琴:

https://jsfiddle.net/vajzyeqw/1/

标签: htmlcss

解决方案


将您的li样式更新为

li {
  width: 10%;
  height: 100%;
  background-color: green;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2.5vw;
}

签出片段

ul{
  position: absolute;
  padding-left: 0px;
  width: 100%;
  height: 15%;
  top: 1%;
  list-style-type: none;
  background-color: #f8d7d7;
}
      
li{
    width: 10%;
    height: 100%;
    background-color: green;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 2.5vw;
  }   
<ul>
  <li>
   Shop
  </li>
</ul>

显示:弯曲;证明内容:中心;对齐项目:居中;字体大小:2.5vw;}


推荐阅读