将框大小设置为“边框”
如何防止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>
尝试使用
.outer {
position: absolute;
border: 1px solid black;
width: min-content;
}
这应该使外箱的宽度尽可能小,而不会挤压内容。
您可以根据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;
}
将框大小设置为“边框”