使用 CSS 控制彈性專案尺寸
要控制 CSS 中彈性專案的尺寸,請使用 `flex` 屬性。將 `flex` 視為彈性專案的長度。`flex` 包括以下屬性:
`flex-grow` − 設定彈性增長因子,即專案相對於其他彈性專案將增長多少。
`flex-shrink` − 設定彈性收縮因子,即專案相對於其他彈性專案將收縮多少。
`flex-basis` − 彈性專案的初始大小。
使用簡寫屬性控制彈性專案尺寸
我們為彈性專案設定了簡寫屬性。這裡,我們為 `flex-grow`、`flex-shrink` 和 `flex-basis` 設定了值:
flex: 2 1 auto;
示例
以下是控制彈性專案尺寸的程式碼:
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .container { display: flex; width: 100%; } div { width: 200px; height: 200px; color: white; text-align: center; font-size: 30px; } .first { background-color: rgb(55, 0, 255); flex: 2 1 auto; } .second { background-color: red; } .third { background-color: rgb(140, 0, 255); } </style> </head> <body> <h1>Controlling flex items dimesions</h1> <div class="container"> <div class="first">First Div</div> <div class="second">Second Div</div> <div class="third">Third Div</div> </div> </body> </html>
使用單個值控制彈性專案尺寸
如果為 `flex` 設定單個無單位的值,則該值用於 `flex-grow` 屬性,如下所示:
flex: 1;
示例
讓我們來看一個使用單個值控制彈性專案尺寸的示例:
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .container { display: flex; width: 100%; } div { width: 200px; height: 200px; color: white; text-align: center; font-size: 30px; } .first { background-color: rgb(55, 0, 255); flex: 1; } .second { background-color: red; } .third { background-color: rgb(140, 0, 255); } </style> </head> <body> <h1>Control the Dimensions of flex items with a single value</h1> <div class="container"> <div class="first">First Div</div> <div class="second">Second Div</div> <div class="third">Third Div</div> </div> </body> </html>
使用兩個值控制彈性專案尺寸
如果為 `flex` 設定兩個無單位的值,則它們分別用於 `flex-grow` 和 `flex-shrink` 屬性,如下所示:
flex: 2 2;
示例
讓我們來看一個控制彈性專案尺寸的示例:
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .container { display: flex; width: 100%; } div { width: 200px; height: 200px; color: white; text-align: center; font-size: 30px; } .first { background-color: rgb(55, 0, 255); flex: 2 2; } .second { background-color: red; } .third { background-color: rgb(140, 0, 255); } </style> </head> <body> <h1>Control the Dimensions of flex items with two values</h1> <div class="container"> <div class="first">First Div</div> <div class="second">Second Div</div> <div class="third">Third Div</div> </div> </body> </html>
廣告