如何防止DIV的宽度扩大?

问题描述 投票:0回答:3

如何防止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); */
}
  <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

html css width
3个回答
1
投票

尝试使用

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

这应该使外箱的宽度尽可能小,而不会挤压内容。


0
投票

您可以根据table-layout属性将容器缩小到最小内容的宽度。

然后您需要通过max-content将.has-content的宽度设置为其实际内容的宽度>

[.dont-expand不需要宽度,除非它本身的单词或图像宽于.has-width,否则它将包裹在宽度内”>

示例:

.outer {
  position: absolute;
  border: 1px solid black;
  display: table;
  width: 0;
}


/* This element sets the width of the container */

.has-width {
  width: max-content;
  margin-top: 10px;
  background: rgba(0, 128, 0, .2);
  border-right: 2px solid green;
  color: #888;
}

.dont-expand {
  /* nothing needed here */
}
.bis {bottom:0}
<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>

<div class="outer bis ">
  <div class="dont-expand">
    How do I get this text to wrap instead of growing the container?
  </div>
  <div class="has-width">
   i'm container's width ! 
  </div>
</div>

https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout

[table-layout CSS属性设置用于布置单元格,行和列的算法。

这里,只有1列,因为.outer的子代没有display重置。这个想法是only

使用table-layout display算法的收缩/扩展本机属性,而不是从div重建HTML表。

将框大小设置为“边框”

.dont-expand {
  /* width: ?? */

  /* This would be nice       */
  /* expand: false;           */

  /* Or this                  */
  /* width: toPx(100%);       */

  /* Or this                  */
  /* width: calc(100% + 0px); */


  box-sizing: border-box;
}

-1
投票

将框大小设置为“边框”

© www.soinside.com 2019 - 2024. All rights reserved.