【问题标题】:How to move part of a div/span to new line?如何将部分 div/span 移动到新行?
【发布时间】:2022-11-22 21:22:31
【问题描述】:

.wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 50px; }

.wide-container, .narrow-container {
  flex: none;
  background-color: #f7f7f7;
  border-radius: 5px;
  padding: 10px 20px;
  box-shadow: 0 5px 35px rgba(0, 0, 0, 0.2);
  border: 1px #c2c2c2 solid; 
}

.wide-container {
  width: 600px; 
}

.narrow-container {
  width: 300px; 
}

.flex {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 0; 
}

.text {
  flex: none;
  padding: 5px 2px;
  background-color: salmon;
  color: white; 
}
<div class="wrapper">
  <div class="wide-container">
    <div class="flex"><span class="text">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></div>
  </div>
  <div class="narrow-container">
    <div class="flex"><span class="text">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></div>
  </div>
</div>

我需要对一段文本应用一些样式,它应该在弹性框内,因为我需要它的一些功能。问题是当没有足够的空间时,文本会溢出:

所以,我需要以某种方式拆分文本,以将样式保持在这样的新行上(在这里手动完成):

更新: 感谢您的回答,但问题比乍一看要复杂一些。答案中的解决方案(到目前为止)导致以下结果:

这意味着换行符在 .text 容器内。如果将此结果与我需要的结果(上面的屏幕截图)进行比较,您就会明白问题所在。

【问题讨论】:

    标签: html css


    【解决方案1】:

    从文本类中删除 flex,它将起作用。

    .text {
      padding: 5px 2px;
      background-color: salmon;
      color: white; 
    }
    

    https://codepen.io/IChoseTheRedPill/pen/zYaRjZb

    【讨论】:

    • 不完全 :( 请检查有问题的更新
    【解决方案2】:

    根据您的描述,您正在寻找 &lt;/br&gt; HTML 元素。刚刚在您的示例中添加了 &lt;/br&gt;

    但是,从您的 .text 类中删除 flex: none 是解决问题的更优雅的方法,如 in another answer 所建议的那样。

    .wrapper {
      display: flex;
      flex-direction: column;
      gap: 20px;
      padding: 50px; }
    
    .wide-container, .narrow-container {
      flex: none;
      background-color: #f7f7f7;
      border-radius: 5px;
      padding: 10px 20px;
      box-shadow: 0 5px 35px rgba(0, 0, 0, 0.2);
      border: 1px #c2c2c2 solid; 
    }
    
    .wide-container {
      width: 600px; 
    }
    
    .narrow-container {
      width: 300px; 
    }
    
    .flex {
      display: flex;
      flex-wrap: wrap;
      gap: 10px 0; 
    }
    
    .text {
      flex: none;
      padding: 5px 2px;
      background-color: salmon;
      color: white; 
    }
    <div class="wrapper">
      <div class="wide-container">
        <div class="flex"><span class="text">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></div>
      </div>
      <div class="narrow-container">
        <div class="flex"><span class="text">Lorem ipsum dolor sit amet consectetur, </br>adipisicing elit. </span></div>
      </div>
    </div>

    【讨论】:

    • 不完全 :( 请检查有问题的更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 2012-06-01
    • 2022-11-03
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多