2017-03-17 26 views
2

这是一个codepen。当您更改视图高度时,请注意紫色元素。他们溢出。我想彻底杀死这条巨龙 - 更重要的是 - 了解发生了什么事情,所以我再也不用打扰你。当视图高度/宽度更改时,如何让子元素保留在父元素中?

https://codepen.io/colbisaurusrex/pen/WpXVxY

body { 
    background-color: #34495E; 
    padding: 5%; 
} 
.container { 
    height: 100vh; 
    display: flex; 
} 
.columnleft { 
    background-color: #2ECC71; 
    height: 100%; 
    width: 30%; 
    margin-right: 10%; 
} 

.leftbox { 
    margin: 10%; 
    height: 100%; 
} 

.box { 
    display: flex; 
    background-color: #1ABC9C; 
    margin: 10%; 
    height: 40%; 
} 

.innerbox { 
    background-color: #3498DB; 
    height: 96%; 
    width: 47%; 
    margin: 2%; 
} 


.columnright { 
    background-color: #2ECC71; 
    height: 100%; 
    width: 60%; 
} 

.row { 
    display: flex; 
    height: 40%; 
    background-color: #9B59B6; 
    width: 80%; 
    margin-right: 10%; 
    margin-left: 10%; 
} 

.rowone { 
    margin-top: 5%; 
    margin-bottom: 5%; 
} 

.rowtwo { 
margin-bottom: 5%; 
} 

回答

1

好的,就像我在你的代码中看到的那样,你正在使用flex buuut ...并不是真的。

我更正了您的columnright,但如果您了解,则可以使用columnleft

你想要实现的是具有相同“高度”的列内的元素并占据整个空间。

因此,这里的修正CSS:

.columnright { 
    background-color: #2ECC71; 
    height: 100%; 
    width: 60%; 
    display: flex; 
    flex-direction: column; 
} 

.row { 
    display: flex; 
    flex: 1; 
    background-color: #9B59B6; 
    width: 80%; 
    margin-right: 10%; 
    margin-left: 10%; 
    margin-top: 20px; 
} 

.rowtwo { 
    margin-bottom: 20px; 
} 

删除一切从rowone。

我用的是flex属性,它定义了一个元素需要多少空间。在这里,每个元素将需要占用1个单位的空间,因此每个元素的高度相同。我还为每个元素添加了一个margin-top来创建一个“内部”填充和一个margin-bottom到最后一个元素。

而且,这里是纠正CodePen:https://codepen.io/anon/pen/vxpBjM

0

好的问题总是受欢迎的。毕竟,这是一个我们自愿帮助别人的时间,所以只要有意义的知识交流发生,它就不再麻烦。

overflow: hidden,overflow: autooverflow: scroll财产添加到包含<div>的款式中,具体取决于您希望达到的效果。有关overflow:属性的更多信息,请参阅w3schools

overflow:属性还有两个子口味,特别是overflow-x:overflow-y:,如果您愿意,每个口味都可以有单独的值。

+0

谢谢你的答案。我意识到溢出属性,但我希望元素能够响应并改变大小。应该已经更清楚了。 – colbisaurusrex

1

好了,让我们来举个例子。你有一个叫做columnright的元素。在里面你有rowonerowtwo

rowone有呈现高度和保证金为:

height: 40%; 
margin-top: 5%; 
margin-bottom: 5%; 

rowtwo有呈现高度和保证金为:

height: 40%; 
margin-bottom: 5%; 

所以40% + 5% + 5% + 40% + 5% = 95%,对不对?它不应该溢出吗?实际上没有

问题:

CSS box model spec指出:

[边]百分率的计算相对于所生成的框的包含块的宽度。请注意,'margin-top'和'margin-bottom'也是如此。如果包含块的宽度取决于这个元素,那么结果布局在CSS 2.1中是未定义的。

所以,当你设置边缘的顶部/底部它是相对于宽度,而不是高度。如果你的元素是矩形(正如你的例子),它会在某个点溢出,因为width高于height

你能做些什么:

那么,这将是最好不要用百分比保证金如果父元素有一个定义的高度。除此之外,如果它适合您的需求,您可以从父母中删除height

+0

我从来不知道百分比是根据父宽而不是高来计算的。谢谢! – colbisaurusrex

相关问题