search
HomeWeb Front-endHTML TutorialBFC之宽度自适应布局篇_html/css_WEB-ITnose

说到自适应布局,我们曾在“抛砖引玉之宽度自适应布局”一文中学习过。当时的核心思想主要是利用float+margin的形式。利用块状元素的流体特性,然后计算出float元素的宽度,并赋予到块状元素的相应margin中。但是这么做是有个缺点的,就是我们每次都得知道float元素的宽度,然后赋予到块状元素的margin。

然而,我们在”BFC之浅析篇”中学习到BFC有一特性:BFC的区域不会与外部浮动元素重叠。并且利用了这一特性,实现了两栏自适应布局。我们再来回顾下。

<!DOCTYPE html>     <head>        <title>BFC</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <style>             .leftDiv {                 width:100px;                 height:100px;                 background:green;                 float:left;             }             .normalDiv {                 height:100px;                 background:pink;                 /*添加overflow:hidden,触发元素BFC*/                 overflow:hidden;             }        </style>    </head>    <body>        <div class="leftDiv"></div>           <div class="normalDiv">        </div>    </body></html>

 运行代码,截图为下

可以看见浮动元素(绿色方块)与div.noramDiv元素的确木有发生重叠,而且我也没有加margin哦。

你也可以自己运行下上述代码,伸缩页面宽度,可以发现也的确是自适应滴。

(PS:上面所示的BFC实现两栏自适应的例子,可以和“float实例讲解”对比学习下,效果会更加哦。)

我们上面是利用的overflow:hidden;来触发div.normalDiv的BFC。在“BFC之浅析篇”中,我们学习到要触发元素成为BFC,有如下几种方法:

1、  float属性不为none

2、  position为absolute或fixed

3、  overflow的值不为visible

4、  display的值为table-cell,table-caption,inline-block中的任何一个。

抛开第三点,overflow的值不为visible,其他几种也适合实现BFC自适应布局?

当然不是咯。

首先,针对第一点float,由于float触发元素BFC后,自身float又带有特性,如将元素包裹化了,破坏了块级元素的流体性,所以不能用来自适应布局。

针对第二点position,又由于position将元素脱离文档流比较严重,因此,更加不能用来自适应布局。

针对,第四点中 display:table-cell,当你设置一个比宽度无线大时,它也不会超过它容器的宽度。

啧啧啧!这不就完美了么。那么我们设置它的宽度为很大很大时,也就可以用来自适应布局了嘛。

看看如下代码

<!DOCTYPE html>     <head>        <title>BFC</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <style>             .leftDiv {                 width:100px;                 height:100px;                 background:green;                 float:left;             }             .normalDiv {                 height:100px;                 background:pink;                 /*添加display:table-cell,且将宽度设置为很大,如9000px*/                 display:table-cell;                 width:9000px;             }        </style>    </head>    <body>        <div class="leftDiv"></div>           <div class="normalDiv"></div>    </body></html>

运行代码后,效果图见上。

ps:自己运行后的体会更深哦,然后伸缩浏览器,哈哈哈,试了就知道,是可以的哦。

针对第四点中的display:table-caption,直接滤过!

针对第四点钟的display:inline-block,由于和float一样具有包裹性,所以滤过。但是,我们曾在"BFC之清除浮动篇&clear"中提到过IE6、7有个hasLayout嘛,在IE6、7中它可是具有流体特性的哦。所以可以解决IE6、7的自适应布局。代码如下

.floatElm {    float: left;}.bftContent {    display: inline-block;}

so, 对触发BFC的方法,能用在自适应布局中的方法如下

overflow(hidden/auto)

缺点:

1、  overflow:hidden当内容过多时,带有剪裁功能

2、  overflow:auto当内容过多时,会出现滚动条

display:inline-block

缺点:

只适用于IE6、7

display:table-cell

缺点:

只适用于IE8+和其他浏览器

终上所述,我们可以得到利用BFC实现自适应布局的通用方法如下:

.floatElm {    float:left;}.bfcContent {    display:table-cell;    width:9000px;/*宽度大到屏幕宽度即可*/    /*hack手段,针对IE6、7*/    *display:inline-block;    *width:auto;}

好了,我们利用这个方法来实现实现三栏布局玩玩。代码如下:

<!--    左右宽度为100px,中间自适应--><!DOCTYPE html>     <head>        <title>BFC</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <style>            .floatLeft,.floatRight {                width:100px;                height:100px;            }            .floatLeft {                /*左浮动触发BFC*/                float:left;                background:green;            }            .floatRight {                /*右浮动触发BFC*/                float:right;                background:yellow;            }            .bfcContent {                /*table-cell触发BFC*/                display:table-cell;                width:9000px;/*宽度大到屏幕宽度即可*/                /*hack手段,针对IE6、7*/                *display:inline-block;                *width:auto;                height:100px;                background:pink;            }         </style>    </head>    <body>        <div class="floatLeft"></div>        <div class="floatRight"></div>        <div class="bfcContent bfcContentStl"></div>    </body></html>

 

不信,自己运行代码,拉动浏览器看看啦。 

 

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
What are self-closing tags? Give an example.What are self-closing tags? Give an example.Apr 27, 2025 am 12:04 AM

Self-closingtagsinHTMLandXMLaretagsthatclosethemselveswithoutneedingaseparateclosingtag,simplifyingmarkupstructureandenhancingcodingefficiency.1)TheyareessentialinXMLforelementswithoutcontent,ensuringwell-formeddocuments.2)InHTML5,usageisflexiblebutr

Beyond HTML: Essential Technologies for Web DevelopmentBeyond HTML: Essential Technologies for Web DevelopmentApr 26, 2025 am 12:04 AM

To build a website with powerful functions and good user experience, HTML alone is not enough. The following technology is also required: JavaScript gives web page dynamic and interactiveness, and real-time changes are achieved by operating DOM. CSS is responsible for the style and layout of the web page to improve aesthetics and user experience. Modern frameworks and libraries such as React, Vue.js and Angular improve development efficiency and code organization structure.

What are boolean attributes in HTML? Give some examples.What are boolean attributes in HTML? Give some examples.Apr 25, 2025 am 12:01 AM

Boolean attributes are special attributes in HTML that are activated without a value. 1. The Boolean attribute controls the behavior of the element by whether it exists or not, such as disabled disable the input box. 2.Their working principle is to change element behavior according to the existence of attributes when the browser parses. 3. The basic usage is to directly add attributes, and the advanced usage can be dynamically controlled through JavaScript. 4. Common mistakes are mistakenly thinking that values ​​need to be set, and the correct writing method should be concise. 5. The best practice is to keep the code concise and use Boolean properties reasonably to optimize web page performance and user experience.

How can you validate your HTML code?How can you validate your HTML code?Apr 24, 2025 am 12:04 AM

HTML code can be cleaner with online validators, integrated tools and automated processes. 1) Use W3CMarkupValidationService to verify HTML code online. 2) Install and configure HTMLHint extension in VisualStudioCode for real-time verification. 3) Use HTMLTidy to automatically verify and clean HTML files in the construction process.

HTML vs. CSS and JavaScript: Comparing Web TechnologiesHTML vs. CSS and JavaScript: Comparing Web TechnologiesApr 23, 2025 am 12:05 AM

HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool