如何使用 CSS Flex 將列 DIV 對齊為左中右?
為了透過在彈性容器的主軸上分配空間來對齊彈性容器的專案,我們使用 CSS 的justify-content屬性。以下是其值:
flex-start - 彈性專案位於容器的起始位置。這是預設值。
flex-end - 彈性專案位於容器的結束位置
center - 彈性專案位於容器的中心
space-between - 彈性專案之間會有間距
space-around - 彈性專案之間以及前後都會有間距
space-evenly - 彈性專案周圍會有相等的間距
語法
CSS justify-content 屬性的語法如下:
Selector { display: flex; justify-content: /*value*/ }
彈性專案之間會有間距
CSS 的justify-content屬性與space-between屬性一起使用,可以讓彈性專案之間有間距。讓我們看一個彈性專案之間有間距的示例。
示例
<!DOCTYPE html> <html> <head> <style> #root { margin: 5%; display: flex; justify-content: space-between; } #one { float:left; box-shadow: inset 0 0 34px #b798e1; } #two { box-shadow: inset 0 0 34px #236fa0; } #three { box-shadow: inset 0 0 34px #43946a; } .element { padding: 7%; border-radius: 15%; } </style> </head> <body> <div id="root"> <div class="element" id="one">1</div> <div class="element" id="two">2</div> <div class="element" id="three">3</div> </div> </body> </html>
彈性專案之間會有相等的間距
CSS 的justify-content屬性與space-evenly屬性一起使用,可以讓彈性專案之間有相等的間距。讓我們看一個示例:
示例
<!DOCTYPE html> <html> <head> <style> #root { margin: 5%; padding: 2%; display: flex; justify-content: space-evenly; box-shadow: inset 0 10px 40px magenta; font-weight: bold; } div > div { padding: 2%; border-radius: 15%; } div:nth-of-type(even) { box-shadow: inset 2px 2px 20px orange; } div > div:nth-of-type(odd) { box-shadow: inset 2px 2px 20px lightblue; } </style> </head> <body> <div id="root"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> </div> </body> </html>
彈性專案位於容器的中心
jusitify-content設定為center以將彈性專案對齊到容器的中心。在這個示例中,我們使用了 CSS 的justify-content屬性與space-evenly屬性,以使其中一個彈性專案之間有相等的間距。
示例
讓我們看一個將彈性專案定位到容器中心的示例:
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .container { display: flex; flex-wrap: wrap; justify-content: space-evenly; background-color: lightblue; } .container1 { align-self: flex-start; display: flex; background-color: rgb(71, 30, 255); width: 200px; margin: 20px; } .container1 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; font-size: 30px; } .container2 { display: flex; background-color: rgb(14, 126, 79); width: 200px; justify-content: center; align-self: flex-start; margin: 20px; } .container2 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; font-size: 30px; } .container3 { display: flex; flex-direction: column; background-color: rgb(168, 60, 10); width: 200px; align-items: center; margin: 20px; } .container3 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; width: 20px; font-size: 30px; } </style> </head> <body> <h1>Flex layout example</h1> <div class="container"> <div class="container1"> <div>1</div> <div>2</div> <div>3</div> </div> <div class="container2"> <div>1</div> <div>2</div> <div>3</div> </div> <div class="container3"> <div>1</div> <div>2</div> <div>3</div> </div> <div class="container1"> <div>1</div> <div>2</div> <div>3</div> </div> </div> </body> </html>
廣告