search
HomeWeb Front-endHTML TutorialCSS3 flex布局应用介绍_html/css_WEB-ITnose

上一篇介绍了flex弹性盒子的语法,本篇用flex来实际布局一下。例如我们以前会用inline-block或float配合%百分比来实现自适应的三列等高布局。但margin / padding计算起来比较复杂,加加减减维护起来很麻烦。用flex弹性盒模型就简单多了。

首先弄出原始的HTML结构,左右侧边栏定宽220px

* { margin: 0; padding: 0; }#header, #footer { width: 100%; }#left, #right { width: 220px; }<div id="header">header</div><div id="page">    <div id="main">main</div>    <div id="left">left</div>    <div id="right">right</div></div><div id="footer">footer</div>

现在将内容容器(#page)设成flex弹性盒模型:#page { display: flex; }

中间main就是个普通的div,因此宽度好像没有自适应,很简单设#main { flex: auto; }即可。因为两个侧边栏没有设flex,因此剩余的宽度将被main独享

main的位置不对,调整位置非常简单,设置#main { … order: 1; }即可。当然别忘了同步给right设#right { … order: 2; }。left不设默认为0。

你可能会疑惑,直接在DOM按left->main->right顺序排列不就行了,为何排列成main->left->right?确实调整DOM顺序也能达到同样效果,但将main越置前,对SEO搜索越友好。这其实并无标准答案,如果你觉得left的内容同样重要,那left->main->right的DOM顺序也是没问题的。

现在只剩最后一步,将footer置底并拉升page部分。先将html和body的height设成100%,为全屏做准备。由于body里包含了header,page,footer,因此为body设置flex弹性盒模型,同时设置flex-direction: column;让3个子元素垂直排列body { … display: flex; flex-direction: column; }

最后将page拉伸就简单了,思路和上面main一样,只要给page设置flex:auto;,因为header和footer没有设flex,因此剩余的高度将被page独享。

* { margin: 0; padding: 0; }html, body { height: 100%; }body {    display: flex;    flex-direction: column;}#header, #footer { width: 100%; }#page {    display: flex;    flex:auto;}#left, #right { width: 220px; }#right { order: 2; }#main {    flex: auto;    order: 1;}

总结一下自适应三列等高布局的思路,body应用垂直的flex模型,让页头,页面,页脚垂直排列,其中只有页面部分有flex:auto;将自适应高度。页面部分应用flex模型,内容,左侧栏,右侧栏将水平排列,其中只有内容部分有flex:auto;将自适应宽度。如果为了SEO优化,在DOM中将内容部分放在左右侧边栏上面的话,通过order调整顺序。

更多布局的例子,可以看看Solved by Flexbox

用flex弹性盒子可以轻松实现等比例布局:

.Grid { display: flex; }.Grid-cell { flex: 1; }<div class="Grid">  <div class="Grid-cell">…</div>  <div class="Grid-cell">…</div>  <div class="Grid-cell">…</div></div>

也可以实现部分固定比例,剩余部分自适应布局:

评论区布局:

代码页面上都有,极其简单,可以自行参考。

总结

flex用于布局真的非常方便,原先用inline-block,float写的一堆既丑且难维护的代码,用flex可以很优雅地实现,什么垂直居中都是浮云。唯一需要的只是时间,等那些旧式浏览器都死透了,弹性盒子的春天就来了。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.