[英]How to align overflowing text horizontally?
我有一些可以溢出父容器的文本:
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%);
}
使用文本缩进:
body { margin: 200px; } .container { width: 100px; height: 50px; background-color: #bbb; text-align: center; } .header { white-space: nowrap; text-indent: -8em; }
<div class="container"> <div> Short Text </div> <div class="header"> Very long text that should not wrap and be center aligned </div> </div>
flexbox 可以轻松做到这一点
body { margin:0 200px; } .container { width: 100px; height: 50px; background-color: #bbb; display:flex; flex-wrap:wrap; justify-content: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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.