2017-02-16 42 views
1

左边的浮动元素会导致元素被推到下一行,一旦空间是粗糙的。你如何将新推入的元素居中放置在剩余的空间中,这样它就不会坐在左边,而是坐在中间。被推动的白色中心元素浮动:左边

让我们拿这段代码为例http://codepen.io/anon/pen/QdPVwe。绿色部分被推到下一行,但它是左对齐的。一旦推动它,它如何在当前窗口宽度中居中?

<div> 
<section></section> 
<section></section> 
<section></section> 
</div> 

section { 
    width: 33%; 
    height:300px; 
    background-color:red; 
    float: left; 
    margin-right: 1%; 

} 

section:last-child { 
    background-color:green; 
    margin-right: 0%; 
} 
div{ 
    width:78%; 
    margin:0 auto; 
} 

回答

1

为此,您可能要重新考虑了不同的策略。 Flex起初有点吓人,但非常有用和强大。

在包装上你可以做display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center;。这出来非常好。

这里是codepen例如: http://codepen.io/sequential/pen/LxvJrr

这里是一个伟大的文章,学习Flexbox的时候。 https://css-tricks.com/snippets/css/a-guide-to-flexbox/

+0

酷技巧。是的,出于某种原因,flex对我来说很可怕。 – sanjihan

+0

@sanjihan对我来说也是,因为flex属性名称不那么直观......就像地狱是一个flex,但它绝对有用。 – Sequential

1

不知道,如果你需要浮动框,但你可以申请display:inline-block;给孩子和text-align:center;父。

section { 
 
    width: 300.33px; 
 
    height:300px; 
 
    background-color:red; 
 
    display:inline-block; 
 
} 
 

 
section:last-child { 
 
    background-color:green; 
 
    margin-right: 0%; 
 
} 
 
div{ 
 
    width:78%; 
 
    margin:0 auto; 
 
    text-align:center; 
 
}
<div> 
 
<section></section><section></section><section></section> 
 
</div>

1

而不是使用float:left;使用display:inline-block;然后添加text-align:center;到父DIV。

section { 
 
    width: 300.33px; 
 
    height:300px; 
 
    background-color:red; 
 
    display:inline-block; 
 
    margin-right: 1%; 
 
} 
 

 
section:last-child { 
 
    background-color:green; 
 
    margin-right: 0%; 
 
} 
 
div{ 
 
    width:78%; 
 
    margin:0 auto; 
 
    text-align:center; 
 
}
<div> 
 
<section></section> 
 
<section></section> 
 
<section></section> 
 
</div>

1

下面是使用flexbox的解决方案。让父母想要中间的元素flex-grow占用剩余的可用空间,然后使用justify-content: center;将其居中放置在该空间中。

.outer { 
 
    width: 78%; 
 
    margin: auto; 
 
} 
 
section { 
 
    width: 300.33px; 
 
    height:300px; 
 
    background-color:red; 
 
    margin-right: 1%; 
 
} 
 
.center section { 
 
    background-color:green; 
 
    margin-right: 0%; 
 
} 
 
.flex { 
 
    display: flex; 
 
} 
 
.center { 
 
    flex-grow: 1; 
 
    justify-content: center; 
 
}
<div class="flex outer"> 
 
    <div class="flex"> 
 
    <section></section> 
 
    <section></section> 
 
    </div> 
 
    <div class="flex center"> 
 
    <section></section> 
 
    </div> 
 
</div>