一、使用Flexbox實現平均分佈
.container { display: flex; justify-content: space-between; } .container div { flex-basis: calc(33.33% - 10px); }
Flexbox布局是常用的實現平均分佈的方式。在父容器中設置display: flex;即可使用彈性盒子布局。justify-content: space-between;可以讓子元素之間平均分佈。然而,flex-basis只是子元素佔據的空間的初始值,如果子元素的內容過多,它仍然可以溢出.
二、使用Grid實現平均分佈
.container { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-gap: 10px; } .container div { width: 100%; }
使用CSS網格布局也可以實現平均分佈。將父容器設置為display: grid;,再設置grid-template-columns為自適應列數,每列的最小寬度為200px,寬度比例為1:1,最終達到平均分佈的效果。此外,使用grid-gap設置子元素之間的邊距.
三、使用定位實現平均分佈
.container { position: relative; margin: 0 auto; max-width: 1200px; } .container div { position: absolute; left: calc(33.33% - 10px); width: calc(33.33% - 10px); } .container div:nth-child(2) { left: calc(66.66% + 20px); }
使用絕對定位和calc()函數也可以實現平均分佈。在父容器中設置position: relative;和max-width,子元素使用position: absolute;進行絕對定位,並使用calc()函數計算子元素的left和width,實現平均分佈。如果需要3個子元素,可以複製第二個子元素的樣式,並設置left和width為適當值.
四、使用偽元素實現平均分佈
.container { position: relative; margin: 0 auto; max-width: 1200px; } .container::before { content: ""; display: table; } .container::after { content: ""; display: table; clear: both; } .container div { float: left; width: calc(33.33% - 10px); margin-right: 10px; } .container div:last-child { margin-right: 0; }
使用偽元素也可以實現平均分佈。在父容器中使用:before和:after偽元素,分別設置display為table和clear:both,以清除浮動。子元素使用float: left進行左浮動,並設置width為子元素空間的初始值(注意減去間距),padding或border-box可以解決子元素內容過多壓縮的問題.
五、使用flex-grow實現平均分佈
.container { display: flex; } .container div { flex: 1; }
使用flex-grow屬性也可以實現平均分佈。在父容器中設置display: flex;,子元素添加flex: 1;即可讓子元素平均分佈。如果子元素的空間不足,它們會等比例地放大以填滿剩餘的空間.
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/189997.html