CSS Flexbox: One-dimensional layout tool
Flexbox, the elastic box layout module, is a powerful tool in CSS for creating one-dimensional layouts such as a series of similar projects. It is especially suitable for single row or single column layouts and can be used as a reliable alternative to Grid layouts in older browsers. This article will provide you with an easy-to-understand Flexbox guide.
Despite the advent of CSS Grid layouts, Flexbox still has its unique value. Although there are some overlaps of functions between the two, they play different roles in the CSS layout. Generally speaking, Flexbox is more suitable for one-dimensional layouts (e.g., a series of similar projects), while Grid is more suitable for two-dimensional layouts (e.g. elements of the entire page).
However, Flexbox can also be used for full page layouts, so in browsers that do not support Grid, it can be used as an effective alternative to Grid layouts. (While Grid has been rapidly improved in most modern browsers, Flexbox still has a wider range of support, which is very practical if you need layouts to work properly in some older browsers.)
Advantages of Flexbox
Some of the advantages of Flexbox include:
- The page content can be laid out in any direction (left, right, down, or even up).
- The visual order of content clips can be reversed or rearranged.
- Items can be "flexibly" resized in response to available space and can be aligned with respect to their containers or to each other.
- Creating a monospace column layout (regardless of the amount of content in each column) is very easy.
<div class="example"> <header>header content here</header> <main class="main"> <nav>nav content here</nav> <div class="content">main content here</div> <aside>aside content here</aside> </main> <footer>footer content here</footer> </div>The first step is to place the elements in
, i.e. .main
and <nav>
, and display them side by side. Without Flexbox, we might use floats to arrange these three elements, but this is not very direct. Furthermore, traditional methods bring a well-known problem: each column has the same height as its content height. So you need to set the same height for all three columns to make them consistent in length, or use some kind of trick. <aside>
Get to use Flexbox The core of
Flexbox is the value of the display
attribute, which needs to be set as a container element. Doing so will turn its child elements into "elastic items". These items will get some convenient properties by default. For example, they are placed side by side, and elements without a specified width will automatically occupy the remaining space. flex
's .main
to display
, its flex
child elements will automatically squeeze between .content
and <nav>
. Isn't it very convenient without any calculations? As an additional bonus, these three elements will magically have the same height. <aside>
<div class="example"> <header>header content here</header> <main class="main"> <nav>nav content here</nav> <div class="content">main content here</div> <aside>aside content here</aside> </main> <footer>footer content here</footer> </div>
Element order: Flexbox order
Attributes
Another property of Flexbox is that it is easy to change the order of elements. Suppose you have built the above layout for the client and she now wants .content
to appear before <nav>
.
Usually, you need to dig into the HTML source code and change the order there. With Flexbox, you can do this task entirely through CSS. Simply set the .content
's order
property to -1 and the content column will be in front.
.main { display: flex; }
In this case, you do not need to explicitly declare the order
value for other columns.
HTML source code using Flexbox independent of CSS style
But your customers are not satisfied yet. She hopes <footer>
is the first element on the page, even before <header>
. Well, Flexbox is your friend again (although in this case it might be better to educate your clients rather than just obey). Since you need to rearrange the internal and external elements, you must set the <div>
rule for display: flex
. Note that you can nest Flex containers in a webpage to achieve the results you want. Because <header>
, <main>
and <footer>
are stacked vertically, you need to set a vertical context first, which you can do quickly with flex-direction: column
. Also, the <footer>
's value is -1, so it will appear on the page first. It's that simple. order
.main { display: flex; } .content { order: -1; }So if you want to change a row of elements to a column or vice versa, you can use the
attribute and set it to flex-direction
or column
(row
is the default): row
How to align items with Flexbox
Flexbox can also align its children very directly horizontally and vertically.You can use
to apply the same alignment to all elements within the Flex container. If you want to set different alignments for each project, use align-items
. The alignment of elements depends on the value of the align-self
attribute. If its value is flex-direction
(i.e., the elements are arranged horizontally), the alignment applies to the vertical axis. If row
is set to flex-direction
(i.e., the elements are arranged vertically), it is applied to the horizontal axis. column
- Set the
align-self
property of each shape to the appropriate value. Possible values ??include:center
,stretch
(elements are positioned to fit their containers),flex-start
,flex-end
, andbaseline
(elements are positioned at the baseline of their containers). - Set the container element to
display: flex
. - Finally, pay attention to the
flex-direction
attribute on the parent container, as its value affects how the child elements are aligned.
<div class="example"> <header>header content here</header> <main class="main"> <nav>nav content here</nav> <div class="content">main content here</div> <aside>aside content here</aside> </main> <footer>footer content here</footer> </div>
If all elements in the parent container need to be aligned in the same way, you can use the align-items
attribute in the parent container. Possible values ??include center
, flex-start
, flex-end
, stretch
(default: the item is stretched to fit its container) and baseline
(the item is positioned at the baseline of its container).
.main { display: flex; }
Use Flexbox to align content
Another alignment attribute is justify-content
, which is very convenient when you want to evenly allocate available space between multiple elements.
Acceptable values ??include: center
, flex-start
, flex-end
, space-between
(there are spaces between items) and space-around
(there are spaces before, between and after the items).
For example, within the <main>
element in the simple HTML template you have been using, you can find three elements: <nav>
, .content
, and <aside>
. Currently, they are all pushed to the left of the page. If you want these three elements to be displayed somehow in order to create some space between them instead of creating spaces separately at the left and right ends of the first and last elements, set .main
(their parent container ) set to justify-content
: space-between
.main { display: flex; } .content { order: -1; }
Use Flexbox to adjust project size
Use the attribute, you can control the length of an element relative to other elements in the Flex container. flex
- — A number that specifies how much an element grows relative to other elastic elements.
flex-grow
- — A number that specifies how much element shrinks relative to other elastic elements.
flex-shrink
- — The length of the element. Acceptable values ??include:
flex-basis
,auto
or numbers followed by "%", "px", "em", or any other unit of length.inherit
for each column: flex: 1
.example { display: flex; flex-direction: column; } footer { order: -1; }If you need the content area to be twice as wide as
and <nav>
, set <aside>
for .content
and leave the other two at 1: flex: 2
More resources
Conclusion
As you can see, if you need to control the location of elements on your website, Flexbox can make our lives much easier. It's very reliable, making any tricks, folding containers or other weird things we have to deal with every day out of date.
As mentioned before, the better option for full page layouts today is the CSS Grid, but it is still worth knowing about the scope of Flexbox's functionality. Flexbox is best for aligning related items in one dimension, but it can also be a convenient alternative to Grid working in older browsers if needed.
FAQs about CSS Flexbox
(Frequently asked questions should be added here to be consistent with the original document)
The above is the detailed content of A Friendly Introduction to Flexbox for Beginners. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin
