Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a DIV from expanding in width?

Tags:

html

css

width

How do I prevent a div from expanding in width?

I'd like .dont-expand to pretend that width: 100%; means "100%, but not counting myself". Basically, compute width: 100%; (ignoring itself), and setting that width in pixels width: Npx; -- in CSS and not JS.

.outer {
  position: absolute;
  border: 1px solid black;
}

/* This element sets the width of the container */
.has-width {
  width: 300px;
  margin-top: 10px;
  background: rgba(0,128,0,.2);
  border-right: 2px solid green;
  color: #888;
}

.dont-expand {
  /* width: ??? */
  
  /* This would be nice       */
  /* expand: false;           */
  
  /* Or this                  */
  /* width: toPx(100%);       */
  
  /* Or this                  */
  /* width: calc(100% + 0px); */
}
  <div class="outer">
    <div class="dont-expand">
      How do I get this text to wrap
      instead of growing the container?
    </div>
    <div class="has-width">
      I should be setting the width of "container".
    </div>
  </div>

jsbin link

like image 636
JS_Riddler Avatar asked Oct 23 '25 15:10

JS_Riddler


2 Answers

It looks like you can make an element "appear" as 0 width to its parent, but still have it expand to the parent's width by doing: width: 0px; min-width: 100%.

This seems to be the cleanest, most browser-compatible solution. It also doesn't require changing the display property, which is a plus.

 /* Make it "shrink-to-fit", either inline-block, or position: absolute */
 .outer {
    /* position: absolute; */
    display: inline-block;
    border: 1px solid black;
  }

  /* This element sets the width of the container */
  .has-width {
    width: 300px;
    margin-top: 10px;
    background: rgba(0,128,0,.2);
    border-right: 2px solid green;
    color: #888;
  }

  /* Appears as 0 width to parent, but then expands to fit. */
  .dont-expand {
    width: 0px;
    min-width: 100%;
  }
<div class="outer">
  <div class="dont-expand">
    How do I get this text to wrap
    instead of growing the container?
  </div>
  <div class="has-width">
    I should be setting the width of "container".
  </div>
</div>
like image 152
JS_Riddler Avatar answered Oct 26 '25 05:10

JS_Riddler


Try using

.outer {
  position: absolute;
  border: 1px solid black;
  width: min-content;
}

This should make it so that the width of the outer box becomes as small as possible, while not squashing content.

like image 33
Daemon Beast Avatar answered Oct 26 '25 04:10

Daemon Beast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!