如何防止DIV宽度扩大?

JS_*_*ler 3 html css width

我该如何预防div宽度扩大?

我想.dont-expand假装这width: 100%;意味着“100%,但不包括我自己”。基本上,计算width: 100%;(忽略自身),并以像素为单位设置宽度width: Npx;——在 CSS 而不是 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); */
}
Run Code Online (Sandbox Code Playgroud)
  <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>
Run Code Online (Sandbox Code Playgroud)

jsbin链接

JS_*_*ler 11

看起来你可以让一个元素在其父元素中“显示”为 0 宽度,但仍然可以通过执行以下操作将其扩展到父元素的宽度:width: 0px; min-width: 100%

这似乎是最干净、最兼容浏览器的解决方案。它还不需要更改display属性,这是一个优点。

 /* 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%;
  }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)