当宽度为 60% 时,在 div 中居中对齐文本

aligning text centrally in a div when the width is 60%

我有一个包含一些文本的 div。我将它居中对齐,但是当我将宽度减小到 60% 时,它会移到屏幕左侧。我怎样才能让我的文本水平居中对齐并将其宽度缩小到 60%?

.tabcontent {
  padding: 6px 12px;
  border-top: none;
}

.tab-card{  
  text-align: center;
  justify-content: center;
  margin-top: 80px;
  width: 60%;
}
<div class="tabcontent">
  <div class="tab-card">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
  </div>
</div>

您可以删除 justify-content center 并添加边距以水平居中。

因为宽度只有 60%,文本可以在 div 内居中,但是包含文本(您的标签卡)的 div 只占其容器的 60%(选项卡内容)。如果您没有另外指定,标签卡将放在标签内容的开头(最左边)并且只占用 60% 的宽度。通过说 margin 0 auto 你是说你想要顶部和底部的边距为 0,并且在左边和右边相等的边距使 div 在它的容器中居中。

看到这个css:

.tabcontent {
     padding: 6px 12px;
     border-top: none;
}
.tab-card {  
     text-align: center;
     margin: 0 auto;
     margin-top: 80px;
     width: 60%;
}

如果您想使用 justify-content,您需要将容器的内容对齐到中心。此外,该容器还需要显示 flex。见下文。

.tabcontent {
    display: flex;
    padding: 6px 12px;
    border-top: none;
    justify-content: center;
}

.tab-card{  
    text-align: center;
    margin-top: 80px;
    width: 60%;
}
.tab-card {
    text-align: center;
    justify-content: center;
    margin: 80px auto;
    width: 60%;
}