htmlcsswhitespacenowrap

CSS - Wrap text in div only when absolutely needed


I have a checkbox with text next to it in a little pop-up window:

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

The problem is that since I have .checkbox-wrapper to be white-space: nowrap;, it goes off the pop-up menu. However, if I remove the white-space: nowrap;, the text wraps way too soon and doesn't take up all the space in the pop-up window. How can I make it so the text only wraps after it hits 100% of the pop-up div's width?


Solution

  • you can use flexbox here, I have attached jsfiddle snippet here.

    .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>