代码之家  ›  专栏  ›  技术社区  ›  Tim

Flexbox:使文本保持水平居中的换行符

  •  2
  • Tim  · 技术社区  · 8 年前

    我有一个flex容器,其中包含一些文本(例如h1),由于容器的宽度,该文本有一个换行符。我试图保持文本内联,这样它就不会自动占据容器宽度的100%,从而保持水平居中,但容器上的Flex会打破这一点。我试过使用 align-self: center 在h1和其他一些事情上没有运气。任何帮助都将不胜感激。

    编辑:我希望文本本身保持左对齐,但h1元素在容器中居中。

    .container {
      width: 250px;
      background-color: tomato;
      
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    
    h1 { 
      display: inline; /* should only take as much space as it needs */
      align-self: center; 
    }
    <div class="container">
       <h1>Text text sdfsdlfkjs</h1>
    </div>
    1 回复  |  直到 8 年前
        1
  •  1
  •   Fernando Hernandez    8 年前

    这就是你要找的吗?

    .container {
     width: 250px;
     background-color:tomato;
     display: flex;
     flex-direction: column;
     justify-content: center;
    }
    
    h1 {
    width: 90%;
    margin-left: auto;
    margin-right: auto;
    border: 1px solid white;
    }