CSS box model

Box Model
CSS Box Model Module Level 3
The CSS box model
Native name
CSS Box Model Module Level 3
StatusW3C Candidate Recommendation Snapshot
Latest versionLevel 3
December 22, 2020 (2020-12-22)[1]
OrganizationWorld Wide Web Consortium
CommitteeCSS Working Group
Editors
  • Elika J. Etemad[1]
  • Bert Bos[2]
  • Anton Prowse[2]
Base standardsCSS
DomainCSS
Websitewww.w3.org/TR/css-box-3/

In web development, the CSS box model refers to how HTML elements are modeled in browser engines and how the dimensions of those HTML elements are derived from CSS properties. It is a fundamental concept for the composition of HTML webpages.[3] The guidelines of the box model are described by web standards World Wide Web Consortium (W3C) specifically the CSS Working Group. For much of the late-1990s and early 2000s there had been non-standard compliant implementations of the box model in mainstream browsers. With the advent of CSS2 in 1998, which introduced the box-sizing property, the problem had mostly been resolved.

Specifics

The Cascading Style Sheets (CSS) specification describes how elements of web pages are displayed by graphical browsers. Section 4 of the CSS1 specification defines a "formatting model" that gives block-level elements—such as p and blockquote—a width and height, and three levels of boxes surrounding it: padding, borders, and margins.[4] While the specification never uses the term "box model" explicitly, the term has become widely used by web developers and web browser vendors.

All HTML elements can be considered "boxes", this includes div tag, p tag, or a tag. Each of those boxes has five modifiable dimensions:

  • the height and width describe dimensions of the actual content of the box (text, images, ...)
  • the padding describes the space between this content and the border of the box
  • the border is any kind of line (solid, dotted, dashed...) surrounding the box, if present
  • the margin is the space around the border

According to the CSS1 specification, released by W3C in 1996 and revised in 1999, when a width or height is explicitly specified for any block-level element, it should determine only the width or height of the visible element, with the padding, borders, and margins applied afterward.[4][5] Before CSS3, this box model was known as W3C box model, in CSS3, it is known as the content-box.

The total width of a box is therefore left-margin + left-border + left-padding + width + right-padding + right-border + right-margin. Similarly, the total height of a box equals top-margin + top-border + top-padding + height + bottom-padding + bottom-border + bottom-margin.

For example, the following CSS code

.myClass {
  width: 200px;
  height: 100px;
  padding: 10px;
  border: solid 10px black;
  margin: 10px;
}

would specify the box dimensions of each block belonging to 'myClass'. Moreover, each such box will have total height 160px and width 260px.

CSS3 introduced the Internet Explorer box model to the standard, known referred to as border-box.[6]

History

The difference in how width is interpreted between the W3C and Internet Explorer box models

Before HTML 4 and CSS, very few HTML elements supported both border and padding, so the definition of the width and height of an element was not very contentious. However, it varied depending on the element. The HTML width attribute of a table defined the width of the table including its border.[7] On the other hand, the HTML width attribute of an image defined the width of the image itself (inside any border).[8] The only element to support padding in those early days was the table cell. Width for the cell was defined as "the suggested width for a cell content in pixels excluding the cell padding."[9]

In 1996, CSS[10] introduced margin, border and padding for many more elements. It adopted a definition width in relation to content, border, margin and padding similar to that for a table cell.[11] This has since become known as the W3C box model.

At the time, very few browser vendors implemented the W3C box model to the letter. The two major browsers at the time, Netscape 4.0 and Internet Explorer 4.0 both defined width and height as the distance from border to border.[12] This has been referred to as the traditional[13] or the Internet Explorer box model.[14]

Internet Explorer in "quirks mode" includes the content, padding and borders within a specified width or height; this results in a narrower or shorter rendering of a box than would result following the standard behavior.[15]

The Internet Explorer box model behavior was often considered a bug, because of the way in which earlier versions of Internet Explorer handle the box model or sizing of elements in a web page, which differs from the standard way recommended by the W3C for the Cascading Style Sheets language.[16][17] As of Internet Explorer 6, the browser supports an alternative rendering mode (called the "standards-compliant mode") which solves this discrepancy. However, for backward compatibility reasons, all versions still behave in the usual, non-standard way by default (see quirks mode). Internet Explorer for Mac is not affected by this non-standard behavior.

Workarounds

Internet Explorer versions 6 and onward are not affected by the bug if the page contains certain HTML document type declarations. These versions maintain the buggy behavior when in quirks mode for reasons of backward compatibility.[18] For example, quirks mode is triggered:

  • When the document type declaration is absent or incomplete;
  • When an HTML 3 or earlier document is encountered;
  • When an HTML 4.0 Transitional or Frameset document type declaration is used and a system identifier (URI) is not present;
  • When an SGML comment or other unrecognized content appears before the document type declaration
  • Internet Explorer 6 also uses quirks mode if there is an XML declaration prior to the document type declaration.[19]

Various workarounds have been devised to force Internet Explorer versions 5 and earlier to display Web pages using the W3C box model. These workarounds generally exploit unrelated bugs in Internet Explorer's CSS selector processing in order to hide certain rules from the browser. The best known of these workarounds is the "box model hack" developed by Tantek Çelik, a former Microsoft employee who developed this idea while working on Internet Explorer for the Macintosh. It involves specifying a width declaration for Internet Explorer for Windows, and then overriding it with another width declaration for CSS-compliant browsers. This second declaration is hidden from Internet Explorer for Windows by exploiting other bugs in the way that it parses CSS rules. The implementation of these CSS "hacks" has been further complicated by the public release of Internet Explorer 7, which has had some issues fixed, but not others, causing undesired results in pages using these hacks.[18]

Box model hacks have proven unreliable because they rely on bugs in browsers' CSS support that may be fixed in later versions. For this reason, some Web developers have instead recommended either avoiding specifying both width and padding for the same element or using conditional comment and/or CSS filters to work around the box model bug in older versions of Internet Explorer.[14][20]

Support for Internet Explorer's box model

Web designer Doug Bowman has said that the original Internet Explorer box model represents a better, more logical approach.[21] Peter-Paul Koch gives the example of a physical box, whose dimensions always refer to the box itself, including potential padding, but never its content.[13] He says that this box model is more useful for graphic designers, who create designs based on the visible width of boxes rather than the width of their content.[22] Bernie Zimmermann says that the Internet Explorer box model is closer to the definition of cell dimensions and padding used in the HTML table model.[23]

The W3C has included a "box-sizing" property in CSS3. When box-sizing: border-box; is specified for an element, any padding or border of the element is drawn inside the specified width and height, "as commonly implemented by legacy HTML user agents".[24] Internet Explorer 8, WebKit browsers such as Apple Safari 5.1+ and Google Chrome, Gecko-based browsers such as Mozilla Firefox 29.0 and later, Opera 7.0 and later, and Konqueror 3.3.2 and later support the CSS3 box-sizing property. Gecko browsers previous than 29.0 support the same functionality using the browser-specific -moz-box-sizing property.[25] border-box is the default box model used in Bootstrap framework.

References

  1. ^ a b Etemad, Elika J., ed. (22 December 2020). "CSS Box Model Module Level 3". W3C. Level 3. CSS Working Group. Retrieved 9 April 2021.
  2. ^ a b Bos, Bert; Prowse, Anton, eds. (6 July 2018). "CSS Basic Box Model Level 3". W3C. 31 July 2018. CSS Working Group. Retrieved 9 April 2021.
  3. ^ "CSS". MDN Web Docs. 23 March 2019. Retrieved 30 March 2019.
  4. ^ a b Wium Lie, Håkon; Bos, Bert (11 January 1999). "Cascading Style Sheets, level 1 § Formatting model". World Wide Web Consortium. Retrieved 26 October 2017.
  5. ^ Håkon Wium Lie; Bert Bos (17 December 1996). "Cascading Style Sheets, level 1". World Wide Web Consortium. Retrieved 9 December 2006.
  6. ^ Peter-Paul Koch (2013). "CSS – box-sizing". quirksmode.org. Retrieved 30 March 2019.
  7. ^ Raggett, Dave (23 January 1996). "The HTML3 Table Model". World Wide Web Consortium. Retrieved 26 October 2017."RFC 1942 HTML Tables". IETF. The default table width is the space between the current left and right margins.
  8. ^ Raggett, Dave; Le Hors, Arnaud; Jacobs, Ian (24 December 1999). "13 Objects, Images, and Applets § Width and height". World Wide Web Consortium. Retrieved 26 October 2017.
  9. ^ Raggett, Dave (14 January 1997). "HTML 3.2 Reference Specification". World Wide Web Consortium. Retrieved 26 October 2017.
  10. ^ Wium Lie, Håkon; Bos, Bert (17 December 1996). "Cascading Style Sheets, level 1". World Wide Web Consortium. Retrieved 26 October 2017.
  11. ^ Wium Lie, Håkon; Bos, Bert (17 December 1996). "Cascading Style Sheets, level 1". World Wide Web Consortium. Retrieved 26 October 2017.
  12. ^ Koch, Peter-Paul. "Box model tweaking". XS4ALL. Retrieved 26 October 2017.
  13. ^ a b Koch, Peter-Paul. "CSS – box-sizing". QuirksMode. Retrieved 26 October 2017.
  14. ^ a b Johansson, Roger (21 December 2006). "Internet Explorer and the CSS box model". 456 Berea Street. Retrieved 26 October 2017.
  15. ^ Lance Silver (March 2001). "CSS Enhancements in Internet Explorer 6". Microsoft Developer Network. Microsoft. Retrieved 24 June 2007.
  16. ^ Shafer, Dan (2005). HTML Utopia: Designing Without Tables Using CSS. Melbourne: Sitepoint. pp. 124 & Appendix C. ISBN 0-9579218-2-9.
  17. ^ Shea, David; Molly E. Holzschlag (2005). The Zen of CSS Design. Berkeley: Peachpit Press. ISBN 0-321-30347-4.
  18. ^ a b Markus Mielke (26 September 2006). "Cascading Style Sheet Compatibility in Internet Explorer 7". Microsoft Developer Network. Microsoft. Retrieved 24 June 2007. "Pages authored under non-strict mode (quirks) will not change behavior in IE7 and will not be affected by broken CSS filters.Pages authored under non-strict mode (or "quirks mode") will not change behavior in IE7."
  19. ^ "!DOCTYPE". Microsoft Developer Network. Microsoft. Retrieved 13 January 2007. "The following examples show how to use the !DOCTYPE declaration to specify the DTD a document conforms to, and to switch Internet Explorer 6 and later to standards-compliant mode."
  20. ^ Arve Bersvendsen (February 2004). "Hack-free CSS for IE". Arve Bersvendsen's weblog. Archived from the original on 15 January 2007. Retrieved 16 January 2007.
  21. ^ "Vorsprung durch Webstandards | Douglas Bowman declares his love to CSS". Vorsprungdurchwebstandards.de. Archived from the original on 14 June 2010. Retrieved 7 July 2010.
  22. ^ "Vorsprung durch Webstandards | Peter-Paul Koch declares his love to CSS". Vorsprungdurchwebstandards.de. Archived from the original on 27 February 2010. Retrieved 7 July 2010.
  23. ^ "Box Model Enlightenment, Bernie Zimmermann". Bernzilla.com. 4 April 2003. Archived from the original on 27 December 2010. Retrieved 7 July 2010.
  24. ^ "CSS3 Basic User Interface Module". World Wide Web Consortium.
  25. ^ "-moz-box-sizing". Mozilla Developer Center. Mozilla. 11 April 2009. Retrieved 11 April 2009. It is possible to use this property to emulate the behavior of browsers that do not correctly support the CSS box model specification.

Read other articles:

Airbus A400MAirbus A400MA300 · A310 · A320 · A330 · A340 · A350 · A380 · A400MTipePesawat transportasi militer jarak jauhTerbang perdana11 Desember 2009[1]Diperkenalkan2013StatusAktif diproduksiPengguna utamaAngkatan Udara PrancisPengguna lainAngkatan Udara Turki Angkatan Udara IndonesiaTahun produksi2007–SekarangJumlah produksi119Harga satuan€ 135 juta (Rp2,10 Triliun)[2][3] Airbus A400M adalah sebuah pesawat transpor militer bermesin empat turboprop. Pesaw...

 

Republik IndiaRepublic of India (Inggris) भारत गणराज्य Bhārat Gaṇarājya (Hindi) ভারতীয় প্রজাতন্ত্র Bhārotiyo Projātôntro (Bengali) جمہوریہ ہندوستان Jamhūriyā Hindustān (Urdu) Bendera Lambang Semboyan: सत्यमेव जयते Satyamēva Jayatē (Hanya kebenaran yang berjaya)Lagu kebangsaan:  जन गण मन Jana Gana Mana (Kamulah Pemimpinnya) Perlihatkan BumiPerlihatkan peta BenderaIb...

 

  لمعانٍ أخرى، طالع أور (توضيح). أور    شعار الاسم الرسمي (بالفرنسية: Eure)‏    الإحداثيات 49°05′00″N 1°00′00″E / 49.083333333333°N 1°E / 49.083333333333; 1   [1] تاريخ التأسيس 4 مارس 1790  تقسيم إداري  البلد فرنسا[2][3]  التقسيم الأعلى نرمندية (1 يناير 2016–)&#...

Company AECL redirects here. For other uses, see AECL (disambiguation). Atomic Energy of Canada LimitedCompany typeCrown corporationIndustryNuclear power researchFounded1952HeadquartersChalk River, Ontario, CanadaKey peopleFred Dermarkar, President and CEORevenue CA$900 million (2017)[citation needed]Total assets CA$1.071 billion (2017)[citation needed]OwnerGovernment of CanadaNumber of employees3500 worldwideSubsidiariesCanadian Nuclear LaboratoriesWebsitewww.aecl.c...

 

Vinoba BhaveSebuah perangko pos yang menampilkan gambar Acharya Vinoba Bhave - 15 Nov 1983LahirVinayak Narahari Bhave(1895-09-11)11 September 1895Gagode, Pen, distrik Raigad, IndiaMeninggal15 November 1982(1982-11-15) (umur 87)Paunar, WardhaNama lainAcharyaDikenal atasGerakan BhoodanPenghargaanPenghargaan Ramon Internasional pada 1958Bharat Ratna pada 1983 Vinayak Narahari Vinoba Bhave (pengucapanⓘ; 11 September 1895 – 15 November 1982) adalah seorang advokat non-kekerasan dan ...

 

Надпись на болотном диалекте языка кри с использованием канадского слогового письма.Содержание 1 Историческая динамика 2 Знание языков на личном уровне 2.1 Родные языки 2.2 Географическое распространение 2.3 Английский язык 2.4 Французский язык 2.5 Двуязычие 3 Уникальные для �...

Crater on Mars This article is about the Martian crater. For the crater on the Moon, see Green (lunar crater). Crater on MarsGreenGullies in Green crater, as seen by HiRISE.PlanetMarsCoordinates52°42′S 8°24′W / 52.7°S 8.4°W / -52.7; -8.4QuadrangleArgyreDiameter184 kmEponymNathan E. Green Green is an impact crater in the Argyre quadrangle of Mars. It is named after Nathan E. Green, a British astronomer (1823-1899).[1] Description Debris flows have been o...

 

此條目可参照英語維基百科相應條目来扩充。 (2021年5月6日)若您熟悉来源语言和主题,请协助参考外语维基百科扩充条目。请勿直接提交机械翻译,也不要翻译不可靠、低品质内容。依版权协议,译文需在编辑摘要注明来源,或于讨论页顶部标记{{Translated page}}标签。 约翰斯顿环礁Kalama Atoll 美國本土外小島嶼 Johnston Atoll 旗幟颂歌:《星條旗》The Star-Spangled Banner約翰斯頓環礁�...

 

Pour les articles homonymes, voir Zhuang. Zhuang Femmes Zhuang de Longzhou, Chine en tenue traditionnelle Populations importantes par région Population totale 18 millions Autres Langues Zhuang Religions Animisme, autres Ethnies liées Tai, Noung, Buyei modifier Le Guangxi en foncé et les provinces de Yunnan, Guangdong, Guizhou et Hunan en clair Les Zhuang (chinois simplifié : 壮族 ; chinois traditionnel : 壯族 ; pinyin : Zhuàngzú ; nom natif...

Sumber referensi dari artikel ini belum dipastikan dan mungkin isinya tidak benar. Mohon periksa, kembangkan artikel ini, dan tambahkan sumber yang benar pada bagian yang diperlukan. (Pelajari cara dan kapan saatnya untuk menghapus pesan templat ini) Gunung Naka (中岳code: ja is deprecated , Naka-dake) adalah gunung dengan ketinggian 3.084 m (10.118 ft) yang terletak di bagian selatan pegunungan Hida yang membentang di Kota Matsumoto, Prefektur Nagano, dan Kota Takayama, Prefektur...

 

British yachtsman David Scott CowperDavid Scott Cowper at Stromness, South Georgia in 2003Photo: David Scott CowperBorn1942Newcastle upon Tyne, EnglandOccupationChartered Building SurveyorKnown forYachtsman, circumnavigator David Scott Cowper is a British yachtsman, and was the first man to sail solo round the world in both directions and was also the first to successfully sail around the world via the Northwest Passage single-handed. Biography Born in 1942, David Cowper was educated at ...

 

Sebuah iklan Ladies' Home Journal 1922 yang menggunakan kata Xmas. Xmas adalah sebuah singkatan umum dari kata Christmas (Natal) . Kata ini terkadang dibaca /ˈɛksməs/ dan memiliki varian seperti Xtemass, yang berasal dari singkatan yang ditulis tangan untuk pengucapan /ˈkrɪsməs/. -mas berasal dari kata bahasa Inggris Lama yang berasal dari bahasa Latin untuk Misa,[1] sementara X berasal dari huruf Yunani Chi, yang merupakan huruf pertama dari kata Yunani Χριστός yang arti...

6°15′18.3″S 106°37′06.4″E / 6.255083°S 106.618444°E / -6.255083; 106.618444 Surya Research Education Center atau SURE Center merupakan suatu pusat penelitian dan pendidikan yang didirikan oleh Prof. Yohanes Surya Ph.D. Gedung yang terletak di kawasan kota mandiri Summarecon Serpong, Tangerang ini diresmikan pada tanggal 29 Maret 2011. Gedung dengan luas 5.800 meter persegi ini akan difungsikan sebagai tempat pelatihan serta persiapan bagi para pelajar yang ...

 

Head of the Catholic Church from 1406 to 1415 PopeGregory XIIBishop of RomePortrait of Gregory XII by van Gent and Berruguete (c. 1476, Ducal Palace, Urbino)ChurchCatholic ChurchPapacy began30 November 1406Papacy ended4 July 1415PredecessorInnocent VIISuccessorMartin VOpposed toAvignon claimant: Benedict XIII Pisan claimants: Alexander V John XXIII OrdersConsecration1390Created cardinal12 June 1405by Innocent VIIPersonal detailsBornAngelo Corraro (or Corario)[1]c. 1327Veni...

 

Questa voce sull'argomento bevande è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. LimonataUn calice di limonataOriginiLuoghi d'origine Francia Regno Unito Italia DettagliCategoriabevanda Ingredienti principalisucco di limone, acqua, zucchero VariantiAranciata La limonata è una bevanda analcolica a base di acqua, succo di limone e zucchero. Indice 1 Storia 2 Caratteristiche 3 Note 4 Bib...

  لمعانٍ أخرى، طالع دانيال برات (توضيح). دانيال برات   معلومات شخصية الميلاد سنة 1806   مقاطعة واشنطن  الوفاة 23 يوليو 1884 (77–78 سنة)  سيراكيوز  مواطنة الولايات المتحدة  مناصب النائب العام لنيويورك   في المنصب1 يناير 1874  – 31 ديسمبر 1875  فرنسيس سي. بارلو&#...

 

Tomer Sisley, Elsa Zylberstein, Valérie Donzelli et Patrick Timsit lors de l'ouverture du printemps du cinéma 2013, à Paris. Félix Moati, Virginie Ledoyen, Max Boublil, Camille Chamoux, Aure Atika, Fred Testot et Emmanuelle Bercot lors de l'ouverture de l'édition 2015. Le Printemps du cinéma est une opération se déroulant chaque année en France depuis 2000, organisée au début du printemps par la Fédération nationale des cinémas français (FNCF), et qui consiste, trois jours dura...

 

A lyga 2019SMSCredit.lt A lyga 2019 Competizione A lyga Sport Calcio Edizione 30ª Organizzatore LFF Date dal 2 marzo 2019al 27 novembre 2019 Luogo  Lituania Partecipanti 8 Formula doppia fase Risultati Vincitore Sūduva(3º titolo) Retrocessioni PalangaStumbras Statistiche Miglior marcatore Tomislav Kiš (27) Incontri disputati 119 Gol segnati 409 (3,44 per incontro) Cronologia della competizione 2018 2020 Manuale Atlantas Kauno ŽalStumbras Palanga Panevėžys Sūduv...

Swedish princess Ingeborg EriksdotterThe seal of Princess Ingeborg of SwedenBornc. 1212Died1254-06-17SpouseBirger JarlIssueRikissa, Queen of Norway Valdemar I Magnus III Catherine, Countess of Anhalt Eric Birgersson Ingeborg, Duchess of Saxony Bengt BirgerssonHouseEricFatherEric X of SwedenMotherRikissa of Denmark Ingeborg Eriksdotter (after 1214 – 17 June 1254) was a Swedish princess, daughter of King Eric X of Sweden, eldest sibling of King Eric XI of Sweden, wife of Birger Jarl...

 

Naval battle where Rome and Rhodes defeat the Seleucids Battle of MyonessusPart of the Roman–Seleucid WarRelief of a Rhodian galleyDateSeptember 190 BCLocationOff Myonessus (modern day Turkey)38°01′28″N 26°30′42″E / 38.0244°N 26.5118°E / 38.0244; 26.5118Result Roman-Rhodian victoryBelligerents Roman Republic Rhodes Seleucid EmpireCommanders and leaders Lucius Aemilius Regillus Eudamus PolyxenidasStrength 80 ships 89 shipsCasualties and losses 2 ships sun...