Flexbox - 弹性容器
要在应用程序中使用 Flexbox,您需要使用 display 属性创建/定义弹性容器。
用法 −
display: flex | inline-flex
此属性接受两个值
flex − 生成块级弹性容器。
inline-flex − 生成内联弹性容器框。
现在,我们将通过示例了解如何使用 display 属性。
弹性
将此值传递给 display 属性后,将创建一个块级弹性容器。它占据父容器(浏览器)的整个宽度。
以下示例演示了如何创建块级弹性容器。在这里,我们创建了六个不同颜色的框,并使用弹性容器来容纳它们。
<!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .container{ display:flex; } .box{ font-size:35px; padding:15px; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html>
它将产生以下结果 −
由于我们已将值 flex 赋给 display 属性,因此容器使用容器(浏览器)的宽度。
您可以通过向容器添加边框来观察这一点,如下所示。
.container { display:inline-flex; border:3px solid black; }
它将产生以下结果 −
内联弹性
将此值传递给 display 属性后,将创建一个内联级弹性容器。它只占用内容所需的位置。
以下示例演示了如何创建内联弹性容器。在这里,我们创建了六个具有不同颜色的框,并使用了内联弹性容器来容纳它们。
<!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .container{ display:inline-flex; border:3px solid black; } .box{ font-size:35px; padding:15px; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html>
它将产生以下结果 −
由于我们使用了内联弹性容器,它只占用了包裹其元素所需的空间。