我有一个固定宽度的容器和一个绝对定位的包含文本的子级。当文本的长度足以包装时,浏览器会非常热心地包装;显示的行比必要的多:
到目前为止,我发现的唯一“解决方案”是将悬停容器的宽度设置为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;
}
答案 0 :(得分:1)
问题是使用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>
答案 1 :(得分:0)
您的父容器的宽度为400px
。保留它100%
。