我有一些文本可以溢出父容器:
body {
margin: 200px;
}
.container {
width: 100px;
height: 50px;
background-color: #bbb;
text-align: center;
}
.header {
white-space: nowrap;
}
<div class="container">
<div class="header">
Short Text
</div>
<div class="header">
Very long text that should not wrap and be center aligned
</div>
</div>
当文本很短时,它会像预期的那样居中对齐。
但是,当文本溢出容器时,它就不再居中对齐了。
不管文本的长度如何水平对齐文本?
期望的结果:
html:
<div class="container">
<div class="header">
<div>Short Text</div>
</div>
<div class="header">
<div>Very long text that should not wrap and be center aligned</div>
</div>
</div>
</body>
</html>
CSS:
body {
margin: 200px;
}
.container {
width: 100px;
height: 50px;
background-color: #bbb;
display: flex;
flex-wrap: wrap;
}
.header {
white-space: nowrap;
position: relative;
left: 50%;
transform: translateX(-50%);
}
此处演示,https://jsfiddle.net/jinny/qs7wL4nv/33/
我是一名优秀的程序员,十分优秀!