当前位置:网站首页>Foundation Consolidation - Flex width is content width

Foundation Consolidation - Flex width is content width

2022-06-23 01:31:00 hhzzcc_

  Official account , You can get a red envelope for takeout every day

When setting labels display: flex The default label has display: block Characteristics of , The width will fill up according to the parent element , as follows

<div class="box-parent">  <div class="box">box</div></div>
.box-parent {
     width: 300px;}
.box {
     display: flex;  background: #fff;}

In the above code box Set up flex Layout , The default width is the same as the parent element 300px, Here's the picture

But most of the time, all we need is to follow the content , Here's the picture

There are three solutions :

Method 1 : The parent element is also set to flex

.box-parent {
     display: flex;  width: 300px;}

because flex Layout sub elements (.box)flex-grow Property defaults to 0( If .box Set up flex-grow: 1 Then it will be full of parent elements ), That is, do not deal with the remaining space , Achieve the effect of maintaining the current content size

Method 2 : Set up box width by fit-content

.box {
     width: fit-content;}

take width Set to fit-content Make an element have ' Inclusion ', The width is also determined by the content , About fit-content also min-content、max-content、fill-available, You can read this article by Xuda

https://www.zhangxinxu.com/wordpress/2016/05/css3-width-max-contnet-min-content-fit-content/

Method 3 :inline-flex

.box {
     display: inline-flex;}

inline-flex and inline-block similar , keep flex At the same time, it is the characteristics of inline elements

原网站

版权声明
本文为[hhzzcc_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220516248659.html