有没有一种方法可以基于单词换行来分割一个 div?

5

我有一个相当简单的div,我用CSS对其进行了样式设置

.text { text-transform: capitalize;
        color: #FFFFFF;
        background: #918a8a;
        opacity: 0.6;
        font-size: 2em;
        height: 80px;
        width: 200px;
     }

它基本上创建了一个灰色的框,内部有一些白色的文本,大小为200px x 80px。

我希望的是,如果文本超过了200px并换行到下一行,会添加一些透明的空格。

因此,例如,如果我有以下HTML:

<div class="text">Here is some text that I typed</div>

我会得到这个:

Sample Image

如果背景是不同的颜色(在这个例子中是蓝色),那么"空白"部分将是透明的,从而允许蓝色显示出来。背景颜色基于用户选择。它也可以是一张图片,所以我无法确定它会是什么样的。

Sample Image 2

假设文本超过了200像素的大小,并且自动换行。没有两个单独的div标签。我也无法控制文本的长度 - 它可以在0到60个字符之间。

作为起点,您可以使用::first-line伪选择器,但我不确定如何对每一行进行操作。 - Jonathan Lam
3个回答

3
您可以使用 repeating-linear-gradient 来实现这个效果:
.text {
  font-size: 30px;
  line-height: 50px;
  background-image: repeating-linear-gradient(
    blue, 
    blue 45px,
    transparent 45px,
    transparent 50px
  );
}

前两个颜色将成为您的“背景”颜色,它们将覆盖您的文本。

接下来的两个颜色是透明的,并且它们将在文本的line-height处结束。

片段:

body {
  background: #cfc;
}

.text {
  color: #FFFFFF;
  width: 300px;
  font-size: 30px;
  line-height: 50px;
  background-image: repeating-linear-gradient(
    blue, 
    blue 45px,
    transparent 45px,
    transparent 50px
  );
}
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>


这正是我一直在寻找的。我从未想过要以那种方式使用“repeating-linear-gradient”。 - Allan

2
我能想出一些基本可行的东西,但是遗憾的是灰色背景不能和容器同宽。你需要在 div 中再添加一个 span 元素。

.text-highlight {
  background:#fff;
  width:200px;
}
.text-highlight span {
  font-size:24px;
  color:#000;
  background:#ccc;
  line-height:42px;
}
<div class="text-highlight">
    <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum, et, ratione. At facere nisi facilis nulla officiis, suscipit saepe quos cum et sequi nostrum amet atque non quam, consequatur dolor.</span>
  </div>

编辑:您可以通过在父容器中指定内联元素的宽度来对齐,但是可能不会看起来那么好。

.text-highlight {
  background:#fff;
  width:200px;
  text-align:justify;
}
.text-highlight span {
  font-size:24px;
  color:#000;
  background:#ccc;
  line-height:42px;
}
<div class="text-highlight">
    <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum, et, ratione. At facere nisi facilis nulla officiis, suscipit saepe quos cum et sequi nostrum amet atque non quam, consequatur dolor.</span>
  </div>


这个解决方案一直很好,直到用户更改了背景颜色。然后它变成了一个白色盒子,上面是黑色字体在灰色背景上。有没有办法使灰色背景之间的空间透明? - Allan

0

我不确定如何使用单个div元素完成它。请检查下面的代码。这可能会对你有所帮助。

<div class="text"><span> Here is some text that I typed </span</div>

.text {
        text-transform: capitalize;
        color: #FFFFFF; 
        opacity: 0.6;
        font-size: 2em;
        height: 80px;
        width: 200px; 
     }
.text span{
        background: #918a8a;
        line-height:20px;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接