简体   繁体   English

CSS div彼此相邻,彼此影响宽度

[英]CSS divs next to each other that affect each others width

I have this problem that I can't seem to figure out. 我有一个似乎无法解决的问题。 After researching I can't seem to find anyone that has solved it. 经过研究,我似乎找不到找到解决方法的人。 I'm not sure that it can be solved in pure CSS, but I have to ask: 我不确定是否可以在纯CSS中解决它,但是我不得不问:

Consider a situation where there are two divs next to each other. 考虑一种情况,其中两个div彼此相邻。 The divs have a known width. div的宽度已知。

The size of the content, however, is not known. 但是,内容的大小未知。 When the content of one div becomes very large, that div should take space from the other, as such: 当一个div的内容变得非常大时,该div应该与另一个div隔开,例如:

This width should only grow if the known width can't accommodate the content. 仅当已知宽度不能容纳内容时,此宽度才应增加。 Likewise, the blue div should grow if its content is very large: 同样,如果蓝色div的内容很大,则它应该会增大:

宽度示例

Is this possible to solve with only CSS, or would I need JS? 是否可以仅使用CSS来解决,还是需要JS?

flexbox and min-width can do that: flexboxmin-width可以做到这一点:

 .wrap { width: 50%; margin: 1em auto; border: 1px solid grey; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } .wrap div { flex: 1 0 auto; max-width: 70%; } .left { background: rgba(255, 0, 0, 0.5); min-width: 30%; } .right { background: rgba(0, 0, 255, 0.5); min-width: 30%; } 
 <div class="wrap"> <div class="left">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur quas incidunt dolorem doloribus asperiores, iure esse voluptatibus dolore cum sint exercitationem minus aspernatur explicabo perspiciatis distinctio expedita.</div> <div class="right"></div> </div> <div class="wrap"> <div class="left"></div> <div class="right">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, accusantium libero omnis, quod ea pariatur porro asperiores enim officia minima!</div> </div> 

if you set a fixed size to div, content will flow in multiple lines instead of div expanding to fit the content. 如果您将固定尺寸设置为div,则内容将以多行显示,而不是div扩展以适合内容。 Instead you need to set minimum width to the div then it can expand, but you will have to set max-width that it can occupy as well so that it wont take full space pushing the second div away. 取而代之的是,您需要为div设置最小宽度,然后它可以扩展,但是您必须设置它也可以占用的max-width,以便不会占用全部空间将第二个div推开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM