简体   繁体   中英

Flexbox div doesn't take the whole width

I'm trying to understand how display:flex works, but whenever I set it, the childs don't take the whole width. I was expecting the three divs getting a 33% of the screen width. What am I doing wrong?

 .flexbox { display: flex; } .flexbox div { border: 1px solid black; padding: 10px; } 
 <div class="flexbox"> <div>One</div> <div>Two</div> <div>Three</div> </div> 

You need to tell flex items to expand. They don't consume free space by default.

The initial setting of flex-basis is auto , which means that items take the size of their content.

The initial setting of flex-grow is 0 , which means that items won't grow across available space.

Add flex: 1 to your items, which is equivalent to: flex: 1 1 0 , which is the shorthand for:

  • flex-grow: 1
  • flex-shrink: 1
  • flex-basis: 0 .

 .flexbox { display: flex; } .flexbox div { flex: 1; /* new */ border: 1px solid black; padding: 10px; } 
 <div class="flexbox"> <div>One</div> <div>Two</div> <div>Three</div> </div> 

Here you go:

<html>
    <head>
        <style>

        .flexbox {
            display: flex;
        }
        .flexbox div {
            flex: 1;
            border: 1px solid black;
            padding: 10px;
        }

        </style>
    </head>
    <body>
        <div class="flexbox">
            <div>One</div>
            <div>Two</div>
            <div>Three</div>
        </div>
    </body>
</html>

In order to make the child elements to grow you will need to add them one of the flex properties. Here is a great article about flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM