【问题标题】:CSS - Wrap text in div only when absolutely neededCSS - 仅在绝对需要时在 div 中包装文本
【发布时间】:2019-05-31 05:04:24
【问题描述】:

我在一个小弹出窗口中有一个带有文本的复选框:

HTML:

<div class="box">
  <div class="checkbox-wrapper">
    <input type="checkbox" class="checkbox" />
    <p class="checkbox-label">Filler filler filler filler filler filler filler filler filler filler filler filler filler filler</p>
  </div>
</div>

CSS:

.box {
  width: 80%;
  height: 100px;
  background-color: #d1d1d1;
  margin-left: 50%;
  transform: translate(-50%, 0);
}

.checkbox-wrapper {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  margin-left: 50%;
  transform: translate(-50%, 0);
}

.checkbox {
  display: inline-block;
}

.checkbox-label {
  display: inline-block;
  color: #2e2e2e;
  font-size: 15px;
  margin: auto;
  margin-left: 10px;
}

JSFiddle

问题是因为我将.checkbox-wrapper 设置为white-space: nowrap;,所以它会从弹出菜单中消失。但是,如果我删除white-space: nowrap;,文本会很快换行,并且不会占用弹出窗口中的所有空间。如何使文本仅在达到弹出 div 宽度的 100% 后才换行?

【问题讨论】:

    标签: html css whitespace nowrap


    【解决方案1】:

    这里可以使用flexbox,我这里附上了jsfiddle sn-p。

    .box {
    		width: 80%;
    		height: 100px;
    		background-color: #d1d1d1;
    		margin-left: 50%;
    		transform: translate(-50%, 0);
    	}
    
    	.checkbox-wrapper {
    		display: flex;
    		max-width: 100%;
    		flex-wrap: nowrap;
    	}
    
    	.checkbox-label {
    		color: #2e2e2e;
    		font-size: 15px;
    		margin-left: 10px;
        margin-top: 0;
    	}
    <div class="box">
    	<div class="checkbox-wrapper">
    		<input type="checkbox" class="checkbox" />
    		<p class="checkbox-label">Filler filler filler filler filler filler filler filler filler filler filler filler filler filler</p>
    	</div>
    </div>

    【讨论】:

    • 谢谢,这似乎有效。如果您在更大的显示器上并且可以将所有内容放在一行中,我确实进行了一项调整以使包装器居中:JSFiddle
    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多