2017-08-18 43 views
2

正如您在下面的代码片段和图片中看到的,我有一个包含主要元素(绿色)和页脚的容器(灰色)。强制元素根据兄弟宽度来包装

页脚本身包含两个元素(蓝色和黄色)。

我想要的是,如果页脚(蓝色+黄色)比主要元素(绿色)宽,则页脚第二个元素(黄色)包装。

我封闭了那些不希望运行的代码片段谁图片:

screenshot from the snippet

我尝试使用的页脚flex-wrap但它只能当我设置的宽度在页脚上,我不想这样做。

.container { 
 
    background-color: grey; 
 
    display: inline-block; 
 
} 
 

 
.narrow-child { 
 
    background-color: green; 
 
    height: 200px; 
 
    width: 100px; 
 
} 
 

 
.large-child { 
 
    background-color: green; 
 
    height: 200px; 
 
    width: 300px; 
 
} 
 

 
.footer { 
 
    display: flex; 
 
    flex-wrap: wrap; 
 
    /*width: 100px;*/ 
 
} 
 

 
.footer-sub-element1 { 
 
    background-color: blue; 
 
    width: 80px; 
 
    height: 50px; 
 
} 
 

 
.footer-sub-element2 { 
 
    background-color: yellow; 
 
    width: 90px; 
 
    height: 50px; 
 
}
<div class="container"> 
 
    <div class="narrow-child"> 
 
    </div> 
 
    <div class="footer"> 
 
    <div class="footer-sub-element1"> 
 
    </div> 
 
    <div class="footer-sub-element2"> 
 
    I want this to wrap 
 
    </div> 
 
    </div> 
 
</div> 
 

 
<div class="container"> 
 
    <div class="large-child"> 
 
    </div> 
 
    <div class="footer"> 
 
    <div class="footer-sub-element1"> 
 
    </div> 
 
    <div class="footer-sub-element2"> 
 
    I don't want this to wrap 
 
    </div> 
 
    </div> 
 
    </div> 
 
</div>

+0

你就会知道页脚子元素的宽度? – sol

+0

@ovokuro不,我不会:( – yannick1976

+0

主要问题是'container'是'inline-block',这意味着它将根据其内容调整大小,直到遇到父宽度,在这种情况下是body。这需要以某种方式约束其宽度以达到你想要的效果 – LGSon

回答

2

.footer宽度不能没有使用JavaScript取决于同级的。解决办法是定义.container而不是.child的宽度。

.container { 
 
    background-color: grey; 
 
    display: inline-block; 
 
} 
 

 
.narrow { 
 
    width: 100px; 
 
} 
 

 
.large { 
 
    width: 300px; 
 
} 
 

 
.child { 
 
    background-color: green; 
 
    height: 200px; 
 
} 
 

 
.footer { 
 
    display: flex; 
 
    flex-wrap: wrap; 
 
    /*width: 100px;*/ 
 
} 
 

 
.footer-sub-element1 { 
 
    background-color: blue; 
 
    width: 80px; 
 
    height: 50px; 
 
} 
 

 
.footer-sub-element2 { 
 
    background-color: yellow; 
 
    width: 90px; 
 
    height: 50px; 
 
}
<div class="container narrow"> 
 
    <div class="child"> 
 
    </div> 
 
    <div class="footer"> 
 
    <div class="footer-sub-element1"> 
 
    </div> 
 
    <div class="footer-sub-element2"> 
 
    I want this to wrap 
 
    </div> 
 
    </div> 
 
</div> 
 

 
<div class="container large"> 
 
    <div class="child"> 
 
    </div> 
 
    <div class="footer"> 
 
    <div class="footer-sub-element1"> 
 
    </div> 
 
    <div class="footer-sub-element2"> 
 
    I don't want this to wrap 
 
    </div> 
 
    </div> 
 
    </div> 
 
</div>

+0

不幸的是,我不能那么干净地(我将不得不添加边框,边距......) – yannick1976

+0

如果确切的解决方案不起作用,基本思路可能仍然有帮助:'.footer'无法使用CSS来调整其宽度以适合'.child'。使用wrapper-'div或者类似技术来达到所需的结果。 – kalsowerus

+0

是的,就是我所做的。喜欢它在没有设置任何宽度的情况下工作(例如,如果绿色元素的宽度取决于其自己的子元素或其中的某些文本) – yannick1976