If the text reaches the absolutely positioned span
element, it should flow around it. If the text within the div
element does not fill an entire line, the entire line should not be colored when hovering over it, but only the text, hence display: inline-block
. So how can I achieve this?
.wrapper {
position: relative;
width: 500px;
}
ul {
list-style: none;
}
ul > li > span {
position: absolute;
right: 0;
font-size: 3em;
line-height: 0.75;
cursor: pointer;
}
ul > li > div {
padding: 10px;
font-size: 0.75em;
}
ul > li > div:hover {
display: inline-block;
}
ul > li:nth-child(1) > div:hover {
background: red;
}
ul > li:nth-child(2) > div:hover {
background: yellow;
}
ul > li:nth-child(3) > div:hover {
background: green;
}
<div class="wrapper">
<ul>
<li>
<span>×</span>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</div>
</li>
<li>
<span>×</span>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</div>
</li>
<li>
<span>×</span>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>
</li>
</ul>
</div>
Use float
combined with width: fit-content
like below:
.wrapper {
width: 500px;
text-align: justify; /* to illustrate the wrapping */
}
ul {
list-style: none;
}
ul > li {
margin: 10px 0;
}
ul > li > span {
float: right; /* use float */
margin-left: 3px;
font-size: 3em;
line-height: 0.6;
cursor: pointer;
}
ul > li > div {
padding: 5px;
font-size: 0.75em;
width: fit-content; /* equivalent to your inline-block */
}
ul > li:nth-child(1) > div:hover {
background: red;
}
ul > li:nth-child(2) > div:hover {
background: yellow;
}
ul > li:nth-child(3) > div:hover {
background: green;
}
<div class="wrapper">
<ul>
<li>
<span>×</span>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.partu rient m ontes, nasce tur ri diculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</div>
</li>
<li>
<span>×</span>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</div>
</li>
<li>
<span>×</span>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>
</li>
</ul>
</div>