[英]Text is breaking using absolute positioning
我有一个小挑战,我在 Stack Overflow 上没有找到任何解决方案。
这就是我得到的:
这就是我想要的:
为了产生这个标题效果,我使用了绝对位置。 我什至不知道标题的宽度和高度。 因此,使用此解决方案时,大文本会中断。
我的 HTML:
<div class="content">
<h1 class="title">February 2015</h1>
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
</div>
我的CSS:
.content {
border: 3px double black;
padding-top: 60px;
position: relative;
width: 350px;
}
.content p { margin: 20px; }
.title {
background: black;
border-radius: 5px;
color: white;
left: 50%;
padding: 10px;
position: absolute;
text-align: center;
transform: translate(-50%, -50%);
top: 0;
}
查看 Codepen 上的示例,让生活更轻松: http ://codepen.io/caio/pen/ZYoyPb
最简单的解决方案是添加white-space: nowrap
。 这样做时, h1
文本不会换行。 (更新示例)
.title {
white-space: nowrap;
background: black;
border-radius: 5px;
color: white;
left: 50%;
padding: 10px;
position: absolute;
text-align: center;
transform: translate(-50%, -50%);
top: 0;
}
此外,您还可以添加text-overflow: ellipsis
/ overflow: hidden
/ width: 100%
以便文本形成省略号并且永远不会换行。 (这里的例子)
在这里,我为您做了一些小的 CSS 更改。
/* Cosmetics */
* { box-sizing: border-box; }
body { margin: 50px; }
p { margin: 0; }
/* True Code */
.content {
border: 3px double black;
padding-top: 30px;
position: relative;
width: 350px;
}
.content p { margin: 20px; }
.title {
background: black;
border-radius: 5px;
color: white;
left: 50%;
padding: 10px;
position: absolute;
text-align: center;
transform: translate(-50%, -50%);
top: 0;
white-space: nowrap;
margin-top: 0px;
}
您的代码是正确的,但 left 属性破坏了您的输出。 由于您的 .content div 设置为相对,因此 .title 将保留在其中。 所以你只需要使用 transform: translate(); 改变你的 .title 的位置。 代码。 瞧,你得到了你想要的输出。
您可能会注意到,我已将 padding-top 赋予 .content 只是为了将标题放置在适当的位置。
更改后的代码如下:
/* Cosmetics */
* { box-sizing: border-box; }
body { margin: 50px; }
p { margin: 0; }
/* True Code */
.content {
border: 3px double black;
padding-top:10px;
position: relative;
width: 350px;
}
.content p { margin: 20px; }
.title {
background: black;
border-radius: 5px;
color: white;
padding: 10px;
position: absolute;
transform: translate(22%,-110%);
}
还有另一种解决方案:
.title {
width: max-content;
}
它得到广泛支持(截至 2019 年 7 月 17 日为 92.25%) https://caniuse.com/#feat=intrinsic-width
有关详细信息,请阅读此答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.