换行时内联块中不必要的空间

时间:2017-10-11 16:41:53

标签: html css

当换行时,是否可以防止内联块右侧出现不必要的空间?这是我清晰的代码



.block1 {
  width: 300px;
  margin-bottom: 30px;
}

.block2 {
  width: 230px;
}

.main-text {
  display: inline-block;
  background-color: rgb(50, 50, 50);
  color: white;
  font-size: 40px;
}

<div class="block1">
  <span class="main-text">Main long text</span>
</div>
<div class="block2">
  <span class="main-text">Main long text</span>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您正在寻找的是一种荧光效果。不幸的是,当display: inline-block在元素周围绘制一个“框”时,它将无效。相反,您可以使用display: inline来实现您的目标。只需用另一个<span>元素包装内部文本,然后说,给它一个.highlighter类:

<span class="main-text">
    <span class="highlighter">Lorem ipsum dolor sit amet</span>
</span>

欺骗内联元素以显示左右填充,您只需在其周围绘制一个盒子阴影即可。左侧的框阴影将具有负x偏移,例如-10px 0 0 <color>,而右侧的x偏移量为x,例如10px 0 0 <color>

.main-text .highlighter {
  background-color: rgb(50,50,50);
  color: white;
  display: inline;
  box-shadow:
    -10px 0 0 rgb(50,50,50),  /* Left box shadow */
    10px 0 0 rgb(50,50,50);   /* Right box shadow */
  padding: 10px 0;            /* Top and bottom paddings */
}

box-shadow的位置参数是:

  1. x-offset
  2. y-offset
  3. blur-radius
  4. -10px 0 0 <color>的方框阴影将生成一个向左偏移10px的框阴影(创建一个假想的左边填充或背景的扩展),没有y偏移且没有模糊。 10px 0 0 <color>的反面相同。

    由于10px框阴影将位于元素的绘图框之外,因此请确保在父级中提供适当的填充/边距,以便它们不会被切断。

    请参阅下面的概念验证示例:

    .block1 {
      width: 300px;
      margin-bottom: 30px;
      padding: 10px;  /* Give this the same value as the box-shadow offsets */
      background-color: steelblue; /* So you can see that the highlighter doesn't fall outside */
    }
    .main-text {
      display: inline-block;
      font-size: 40px;
      margin-bottom: 40px; /* For presentational purposes only */
    }
    .main-text .highlighter {
      background-color: rgb(50,50,50);
      color: white;
      display: inline;
      line-height: 1.5;           /* Line height used so backgrounds don't overlap */
      box-shadow:
        -10px 0 0 rgb(50,50,50),  /* Left box shadow */
        10px 0 0 rgb(50,50,50);   /* Right box shadow */
      padding: 10px 0;            /* Top and bottom paddings */
    }
    <div class="block1">
      <span class="main-text"><span class="highlighter">Lorem ipsum</span></span>
      
      <span class="main-text"><span class="highlighter">Lorem ipsum dolor sit amet</span></span>
      
      <span class="main-text"><span class="highlighter">Lorem ipsum dolor sit amet, I am a very long title</span></span>
    </div>

答案 1 :(得分:0)

&#13;
&#13;
.block1 {
  width: 300px;
  margin-bottom: 30px;
}

.block2 {
  width: 230px;
}

.main-text {
  display: inline;
  background-color: rgb(50, 50, 50);
  color: white;
  font-size: 40px;
}
&#13;
<div class="block1">
  <span class="main-text">Main long text</span>
</div>
<div class="block2">
  <span class="main-text">Main long text</span>
</div>
&#13;
&#13;
&#13;