有没有办法有条件地将特定样式应用于元素溢出?
例如如果我要说:
<div>
This text is very long, no really it is extremely long; it just goes on and on and on and on. You might say it's a bit like the Duracell(R) bunny, but without the batteries, and the floppy ears.
</div>
和
div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
// TODO: is there any way to only apply this rule if the text is overflowing?
div {
background-color: red;
}
有没有办法使用纯 CSS 来使背景颜色:红色规则仅在文本溢出时适用?
注意:我可以看到一种使用 javascript 执行此操作的方法;我只是想知道是否有纯 CSS 的方法来做到这一点。
我一直在寻找具有相同功能的东西,这是我发现的第一个问题,遗憾的是没有答案。然而,更改我的搜索词发现了以下问题:“检查元素的内容是否溢出?”带有CSS唯一答案。
注意:此示例在文本后面有阴影,当阴影和文本具有相同颜色时,这不是问题。
对上面链接的答案稍作修改的片段。
body {
display: flex;
}
.scrollbox {
width: 200px;
/* Required */
overflow: auto;
max-height: 180px;
background:
/* Shadow covers */
linear-gradient(white 30%, rgba(255,255,255,0)),
linear-gradient(rgba(255,255,255,0), white 70%) 0 100%,
/* Shadows */
radial-gradient(50% 0, farthest-side, rgba(0,0,0,.2), rgba(0,0,0,0)),
radial-gradient(50% 100%,farthest-side, rgba(0,0,0,.2), rgba(0,0,0,0)) 0 100%;
background:
/* Shadow covers */
linear-gradient(white 30%, rgba(255,255,255,0)),
linear-gradient(rgba(255,255,255,0), white 70%) 0 100%,
/* Shadows */
radial-gradient(farthest-side at 50% 0, rgba(0,0,0,.2), rgba(0,0,0,0)),
radial-gradient(farthest-side at 50% 100%, rgba(0,0,0,.2), rgba(0,0,0,0)) 0 100%;
background-repeat: no-repeat;
background-color: white;
background-size: 100% 40px, 100% 40px, 100% 14px, 100% 14px;
/* Opera doesn't support this in the shorthand */
background-attachment: local, local, scroll, scroll;
}
<div class="scrollbox">
<ul>
<li>Not enough content to scroll</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<div class="scrollbox">
<ul>
<li>Ah! Scroll below!</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>The end!</li>
<li>No shadow there.</li>
</ul>
</div>