css - Flexbox:保持带换行符的文本水平居中

标签 css flexbox

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

编辑:我想让文本本身保持左对齐,但让 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>

最佳答案

这是你要找的吗?

.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;
}

关于css - Flexbox:保持带换行符的文本水平居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49714696/

相关文章:

css - IE8 漏洞 : Am I missing something in the CSS?

css - 使用绝对位置时下拉菜单根本不可见

html - 输入元素在引导网格中具有意外的包装行为

css - Bootstrap 4方格

javascript - 如何将三个动画进度条与图像水平对齐?

css - 内部 flexbox 否决外部 flexbox 上的 flex-grow

css - ng-bootstrap,点击,更改下拉图标

html - HTML 复选框输入的标签(分布在多行上)可以与第一行标签的开头对齐多长时间?

javascript - Grunt 不要连接 css 和 jquery 文件

html - 使用 flexbox 防止下一行占据上一行中最高元素的高度?