gpt4 book ai didi

css - 我怎样才能防止绝对定位的 child 急切的文字换行?

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:23 25 4
gpt4 key购买 nike

我有一个固定宽度的容器和一个包含文本的绝对定位子项。当文本足够长可以换行时,浏览器会非常急切地换行;显示比必要更多的行:

Eager text wrap

到目前为止,我找到的唯一“解决方案”是将悬停容器的宽度设置为:90%。但这对短文本不利!

这是一个 jsfiddle:http://jsfiddle.net/zbLvd7on/

一些 HTML:

<div id="container">
Container
<div id="child">
This is a long enough text to wrap. I want it to wrap but I also want it to expand to 90% width and mostly fill its parent. Why does it wrap so eagerly?
</div>
</div>

一些CSS:

#container {
position: relative;
background: #c0c0c0;
color: black;
width: 400px;
cursor: pointer;
padding: 4px;
text-align: center;
font-family: sans-serif;
margin-top: 40px;
}

#child {
content: "";
padding: 4px;
background: #f0f0f0;
font-size: 10px;
position: absolute;
left: 50%;
transform: translateX(-50%);
top: calc(100% + 5px);
z-index: 1;
max-width: 90%;
display: block;
}

最佳答案

问题是 left:50% 的使用。一个想法是考虑像下面这样的文本和中心的另一个包装器:

#ex {
position: relative;
background: #c0c0c0;
color: black;
width: 400px;
cursor: pointer;
padding: 4px;
text-align: center;
font-family: sans-serif;
margin-top: 40px;
}
span {
display:inline-block;
max-width: 90%;
background: #f0f0f0;
padding: 4px;
}
#after,
#before{
font-size: 10px;
position: absolute;
left: 0;
right:0;
top: calc(100% + 5px);
z-index: 1;
text-align:center;
}

#before {
top:auto;
bottom:calc(100% + 5px);
}
<div id="ex">
Container
<div id="before">
<span>Short text</span>
</div>
<div id="after">
<span>This is a long enough text to wrap. I want it to wrap but I also want it to expand to 90% width and mostly fill its parent. Why does it wrap so eagerly?</span>
</div>
</div>

如果您不能使用额外的元素,另一种方法是考虑 fit-content 值在宽度范围内 ( https://caniuse.com/#feat=intrinsic-width):

#ex {
position: relative;
background: #c0c0c0;
color: black;
width: 400px;
cursor: pointer;
padding: 4px;
text-align: center;
font-family: sans-serif;
margin-top: 40px;
}

#ex::after,
#ex::before{
content: "This is a long enough text to wrap. I want it to wrap but I also want it to expand to 90% width and mostly fill its parent. Why does it wrap so eagerly?";
padding: 4px;
background: #f0f0f0;
font-size: 10px;
position: absolute;
width:fit-content;
margin:0 auto;
left:0;
right:0;
top: calc(100% + 5px);
z-index: 1;
max-width: 90%;
}

#ex::before {
content: "Short text";
top:auto;
bottom: calc(100% + 5px);
}
<div id="ex">
Container
</div>

关于css - 我怎样才能防止绝对定位的 child 急切的文字换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53258472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com