search
HomeWeb Front-endCSS TutorialGetting started with div+css layout_CSS/HTML

你正在學習CSS佈局嗎?是不是還不能完全掌握純CSS佈局?通常有兩種情況阻礙你的學習:

第一種可能是你還沒理解CSS處理頁面的原理。在你考慮你的頁面整體表現效果前,你應先考慮內容的語意和結構,然後再針對語意、結構添加CSS。這篇文章將告訴你應該如何把HTML結構化。

另一個原因是你對那些非常熟悉的表現層屬性(例如:cellpadding,、hspace、align="left"等等)束手無策,不知道該轉換成對應的什麼CSS語句。當你解決了第一個問題,知道如何結構化你的HTML,我再給出一個列表,詳細列出原來的表現屬性用什麼CSS來代替。

結構化HTML
我們剛學習網頁製作時,總是先考慮怎麼設計,考慮那些圖片、字體、顏色、以及版面方案。然後我們用Photoshop或Fireworks畫出來、切割成小圖。最後再透過編輯HTML將所有設計還原表現在頁面上。

如果你希望你的HTML頁面用CSS佈局(是CSS-friendly的),你需要回頭重來,先不考慮“外觀”,要先思考你的頁面內容的語義和結構。

外觀並不是最重要的。一個結構良好的HTML頁面可以以任何外觀表現出來,CSS Zen Garden就是一個典型的例子。 CSS Zen Garden幫助我們最終認識到CSS的強大力量。

HTML不只在電腦螢幕上閱讀。你用photoshop精心設計的畫面可能無法顯示在PDA、行動電話和螢幕閱讀機上。但是一個結構良好的HTML頁面可以透過CSS的不同定義,顯示在任何地方,任何網路設備上。

開始思考
首先要學習什麼是"結構",有些作家也稱之為"語意"。這個術語的意思是你需要分析你的內容區塊,以及每個內容服務的目的,然後再根據這些內容目的建立起對應的HTML結構。

如果你坐下來仔細分析和規劃你的頁面結構,你可能得到類似這樣的幾塊:

標誌和站點名稱 
主頁內容 
站點導航(主選單) 
子選單 
搜尋框 
功能區(例如購物車、收銀台) 
頁腳(版權及相關法律聲明) 
我們通常採用DIV元素來將這些結構定義出來,類似這樣:















This is not a layout, but a structure. This is a semantic description of content blocks. When you understand your structure, you can add the corresponding ID to the DIV. Any content block can be contained within a DIV container, and another DIV can be nested within it. Content blocks can contain any HTML element---titles, paragraphs, images, tables, lists, etc.

According to the above, you already know how to structure HTML, and now you can define layout and style. Each content block can be placed anywhere on the page, and the color, font, border, background, alignment properties, etc. of the block can be specified.

Using selectors is a wonderful thing
The name of the id is a means of controlling a certain content block. By surrounding this content block with a DIV and adding a unique id, you can use CSS to select it. Converter to precisely define the appearance of each page element, including titles, lists, pictures, links or paragraphs, etc. For example, if you write a CSS rule for #header, it can be completely different from the image rule in #content.

Another example is: you can define link styles in different content blocks through different rules. Something like this: #globalnav a:link or #subnav a:link or #content a:link. You can also define different styles for the same element in different content blocks. For example, define the styles of p in #content and #footer respectively through #content p and #footer p. Structurally speaking, your page is composed of pictures, links, lists, paragraphs, etc. These elements themselves do not affect which network device they are displayed on (PDA, mobile phone or Internet TV). They can be defined as Any performance appearance.

A carefully structured HTML page is very simple, and every element is used for structural purposes. When you want to indent a paragraph, you don't need to use the blockquote tag. Just use the p tag and add a CSS margin rule to p to achieve the indentation purpose. p is a structured tag and margin is a presentation attribute. The former belongs to HTML and the latter belongs to CSS. (This is the separation of structure and presentation.)

There are almost no presentation attribute tags in a well-structured HTML page. The code is very clean and concise. For example, the original code can now only write
in HTML, and all things that control the performance are written in CSS. In structured HTML, table is a table, not anything else (such as being used for layout and positioning).

Practice the structure yourself
The above mentioned is only the most basic structure. In actual application, you can adjust the content blocks according to your needs. DIV nesting often occurs, and you will see that there are other layers in the "container" layer, with a structure similar to this:





    a list






    another list






Nested div elements allow you to define more CSS rules to control presentation. For example: you can give #navcontainer a rule to center the list on the right, and #globalnav a rule to center the list on the left, and # Another completely different performance of subnav's list.

Replace traditional methods with CSS
The following list will help you replace traditional methods with CSS:

HTML attributes and corresponding CSS methods
HTML attributes CSS methods Description
align="left"

align="right" float: left;

float: right; Use CSS to float any element: pictures, paragraphs, divs, titles, tables, lists, etc. etc.

When you use the float attribute, you must define a width for the floating element.

marginwidth="0" leftmargin="0" marginheight="0" topmargin="0" margin: 0; Using CSS, margin can be set on any element, not just the body element. More importantly , you can specify the margin values ​​of the element's top, right, bottom and left respectively.

vlink="#333399" alink="#000000" link="#3333FF" a:link #3ff;

a:visited: #339;

a :hover: #999;

a:active: #00f;
In HTML, the color of the link is defined as an attribute value of the body. The link style is the same throughout the page. Using CSS selectors, link styles can be different in different parts of the page.

bgcolor="#FFFFFF" background-color: #fff; In CSS, the background color can be defined for any element, not just body and table elements.

bordercolor="#FFFFFF" border-color: #fff; Any element can set a border (boeder), you can define top, right, bottom and left respectively

border="3 "

cellspacing="3" border-width: 3px; Using CSS, you can define the border of the table as a unified style, or you can define the color, size and style of the top, right, bottom and left borders respectively.

You can use table, td or th these selectors.

If you need to set a borderless effect, you can use CSS definition: border-collapse: collapse;









clear: left;

clear: right;

clear: both;
Many 2-column or 3-column layouts use the float attribute for positioning. If you define a background color or background image in the floating layer, you can use the clear attribute.

cellpadding="3"

vspace="3"

hspace= "3" padding: 3px; Using CSS, any element can set the padding attribute. Similarly, padding can be set to top, right, bottom and left respectively. padding is transparent.

align="center" text-align: center;

margin-right: auto; margin-left: auto;
Text-align only applies to text.

Block-level elements like div, p can be horizontally centered using margin-right: auto; and margin-left: auto;


Some regrettable techniques and working conditions
Due to the imperfect support of CSS by browsers, we sometimes have to adopt some tricks (hacks) or establish an environment (Workarounds) to allow CSS to achieve the same effect as traditional methods. For example, block-level elements sometimes need to use horizontal centering techniques, box model bug techniques, etc. All of these techniques are detailed in Molly Holzschlag's article "Integrated Web Design: Strategies for Long-Term CSS Hack Management".

Another resource site for CSS tips is Big John and Holly Bergevin’s “Position is Everything”.

Understanding floating behavior
Eric Meyer's "Containing Floats" will help you master how to use float attributes for layout. Float elements sometimes need to be cleared. Reading "How To Clear Floats Without Structural Markup" will be very helpful.

More help
The existing CSS Discussion list is a good resource, it collects information from a WiKiA discussion group, including a summary of CSS layout (css-discuss.incutio.com/ ?page=CssLayouts), CSS Tips Summary (css-discuss.incutio.com/?page=CssHack) and more
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
CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

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.

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