2017-02-16 41 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>