Everyone of you will run into problems, and more than likely, lots of problems, and you have to tackle them one by one, for usually becomes a mess if there are too many problems all at once. The solution, then, is to solve the problems one by one, until they’re all gone. In part 1 of this document shows how to isolate the problem so that you can solve it, and in part 2 provides some clarification on confusing issues in CSS.
Creating a Problem Free Document
The first step is to copy and paste the basic HTML5 code into your text editor and to give it a page a name that contains no spaces and ends with .html. You add a link to an external CSS style sheet in the header of the document and include the CSS reset at the top of your external CSS style sheet.
In an ideal world, you add code and validate every few minutes, staying on the strait and narrow path. This is a lot better than running into a problem and finding out that you have 153 errors because you forgot to validate regularly. Yes, using HTML and CSS is really problem solving. You follow the rules, and each one of them is very simple, but add them all together to create a complicated layout, and that is were the trouble begins.
One way to keep trouble from your door is to organize your document into regions, like a wireframe, diving up your page into independent locales. That way, if there is a problem you know where it is.
It is a good idea to use comments <!-- comments --> or inside of the external style sheet /* comments */ to identify what the code is doing. It is amazing how much we forget when asked to redo something on a job that was done a year ago.
It is also possible to “comment out” parts of the code you temporarily want to suppress, which means that you use this comment code to remove the HTMl markup and CSS rules that you want the browser to ignore.
Troubleshooting When You Have Problems
There are times when you have been busy coding and whatever you are trying to do just does not work. When a document becomes complicated enough, fining an unclosed div can be a problem. That’s when you have to troubleshoot the document.
Troubleshooting comes into play when you have trouble but you do not know the cause of that problem, so you have to figure out where in the code the trouble is, and then fix the problem.
Unfortunately the problem is not blinking on and off so as to attract your attention. Instead, you have to hunt it down.
This becomes more difficult if you have not been validating regularly. It can even happen with pages that do validate, though that is much less likely, so I ask you to validate your documents regularly.
Tools like Firebug, Web Developer and the Inspect Element in the Safari and Chrome browsers can be very helpful. In the last two browsers, right-click on an element and inspect element is the last item in the popup menu. You can activate this inspection and debugging tool in the preferences.
These tools allow you to inspect your CSS, but that does not always indicate what is causing the problem. You might have written the HTML markup or CSS rule incorrectly somewhere else.
Process of Elimination
If you think that your problem is with one or another CSS definition, start testing them by adding something obvious, like background-color: red;, outline: 1px solid green or something like that.
If you still cannot locate the problem, start removing the rules one at a time, until you find where the problem is. The same is true of the HTML, in case you cannot find the tag that’s not closed, misspelled, etc. You sometimes have to remove a lot, and you can speed up the process by eliminating half, testing it, and if the problem goes away, test the other half, and so on.
Once you have found what causes the problem, you can fix it, circumvent it, etc.
Validate!
Key to working on the web, especially as you are starting out, is to validate often, as it will let you know as soon as you have gone off track, so please use this service often!
This is taken from CSS-tricks.com, one of the great websites to go to.
If you’re a pro, it’s easy to forget the confusion you felt when you just started learning CSS. Just for fun, let’s try and remember some of those little weird confusing moments. I’ll start us out by listing some random ones I remember and have picked up on while helping others recently. Then you folks take it from there in the comments.
These aren’t huge big things like broken layouts in IE or which vendor prefixes should you be using. It’s the little fundamental stuff, like tiny differences in syntax that change meaning in a big way.
Tag qualifying
What’s the difference between these two things?
.class { }
p.class { }
The first one will select any element with that class name. The second one will only select paragraph elements with that class name.
The first is more generically useful. The styling you apply with that class may be useful to multiple types of elements. Even if it’s not today, it might be tomorrow. It’s also faster for the browser to understand and apply.
It’s a fairly rare case that you’d want to use the second example. It would only be if you wanted to re-use the same class name for multiple elements but have them to different things.
The first example there is very different because of the space character between .class and div. The stuff before the space and the stuff after the space select different elements. The first part is “select any element with this class name” and the second part is “select any div”. Put them together with a space and you get “select any div that is a descendant of any element with this class name”.
The second doesn’t involve any of that descendant business. It’s a tag-qualified selector like discussed above.
If the above CSS was the only CSS on the page, the results would be like this:
<div class="class">
<h2>
<div>Would be red</div>
</h2>
<div>Would be red</div>
Would be green
<div>
<div>Would be black</div>
Why use ID’s at all?
It seems like as far as CSS is concerned, using classes and using ID’s is the exact same thing.
#id { color: red; }
.class { color: green; }
It’s just an attribute and it’s a seemingly arbitrary difference in syntax depending on which one you use. The results are predictable:
<div id="id">Would be red</div>
<span id="id">Would be red</div>
<div class="class">Would be green</div>
<span class="class">Would be green</div>
You might have learned ID’s are “supposed” to be unique, as in, only have one element per page that uses it. But you’ve slipped up before and it doesn’t seem to matter, the CSS applies just fine.
Then you start getting conflicting information. Some tools and philosophy) teach that ID’s aren’t good for styling. Some articles tell you they are the most efficient. Perhaps you work with a JavaScript developer who tells you they need ID’s on everything because it makes their job way easier.
Confusion abound here. Turns out, everybody is kinda right. Here are the facts:
CSS doesn’t care much which you use, as far as actually applying styling. ID’s are technically faster for a browser rendering engine, but other than the most extreme of circumstances you’ll probably never notice a speed difference.
JavaScript cares very much about ID’s. It can be noticeably faster for JavaScript to find an element by an ID. And this is where the “uniqueness” is very important. JavaScript will only find the “first” element with that ID, so if you have multiple on the page, confusion may ensue.
ID’s have an infinitely higher specificity value than classes. If there is an element with an ID and a class and they both apply styles, the styles applied by the ID will take precedence over the styles applied by the class. This can be useful, this can be a hindrance.
My personal philosophy is to use ID’s on stuff that I absolutely know there will only ever be one of and will not benefit from properties from a class name shared with other elements.
Buried hovers
What’s going on here?
div { color: red; }
div:hover div { color: green; }
:hover is a selector which only applies itself when the mouse is over a particular element. What is weird here is that you don’t necessarily have to apply styles to that element being hovered over. In this case, we are applying styling only to descendant divs when the parent div is hovered. So:
<div>
I will be red all the time
<div>
I will be red, unless that top
div is hovered (but not necessarily me)
and then I'll be green.
</div>
I will be red all the time
</div>
Whitespace doesn’t matter
This:
div{color:red}
Is the exact same as:
div {
color : red
}
You do need spaces in selectors to make decendent selectors (e.g. ulli { } is absolutely not the same as ul li { }) but other than that you should use whitespace however makes looking and working with your CSS comfortable.
Notice the missing semicolon on that property in the example above. You can omit that if it’s the last property in the group. Personally I never do as if you add more property/values later and forget to add the semicolon to the previous line, that’s a problem. Because whitespace is so free, it will continue to read the next line as part of the value of the previous line.
Example of the problem:
div {
-webkit-border-radius: 10px
-moz-border-radius: 10px
border-radius: 10px
}
The whitespace is fine. The no-semicolon on the last one is fine. But the first two property/value pairs don’t have semicolons and will totally screw up and not work.
We started out the semester with a plain HTML5 template. It used to be that not all browsers would interpret HTML or CSS the same way, and there was a need for a boilerplate that normalized all the differences, but those days are gone. Google’s rendering engine Chromium split from Apple’s Webkit, and the only other rendering engine is Firefox’s Mozilla, and its future does not always look secure, which is unfortunate. Slim pickings compared to the way it used to be. Competition and diversity are good, but no one misses Explorer’s many exceptions.
Using a boilerplate will make your life a little more complicated, but it takes care of any contingencies that make building a professional website more challenging.
The HTML5 Boilerplate
The HTML5 Boilerplate helps you build fast, robust, and adaptable web apps or sites. Kick-start your project with the combined knowledge and effort of 100s of developers, all in one little package.
We are using the most recent HTML5 boilerplate. I expect everyone to use it as the basis for the midterm and final. Head on over to the Support Documents
The boilerplate is everything for everybody, from the novice to the professional, so it’s stacked with goodies that you would not be able to incorporate on your own at the level you are at.
Features
HTML5 ready. Use the new elements with confidence.
Includes [Normalize.css](http://necolas.github.com/normalize.css/) for CSS normalizations and common bug fixes.
The latest [jQuery](http://jquery.com/) via CDN, with a local fallback.
The latest [Modernizr](http://modernizr.com/) build for feature detection.
Placeholder CSS Media Queries.
Useful CSS helpers.
Default print CSS, performance optimized.
An optimized Google Analytics snippet.
Apache server caching, compression, and other configuration defaults for Grade-A performance.
Cross-domain Ajax and Flash.
“Delete-key friendly.” Easy to strip out parts you don’t need.
Extensive inline and accompanying documentation.
Documentation
Take a look at the table of contents. This documentation is bundled with the project, which makes it readily available for offline reading.
If You Want To Know More
There is comprehensive documentation. Learn more about HTML5, browser compatibility, javascript libraries and all the other goodies that make up this boilerplate.
Instructions in a Nutshell
Implementing the HTLM5 Boilerplate is easy. Transfer your CSS to the external CSS style sheet provided, and the HTML markup to the index.html file where indicated.
Where to put the CSS
Enter your CSS code on the external style sheet provided. It is already linked to the index.html page.
The CSS style sheet normalizes the browser in a more nuanced way than the browser reset. These have to come before your own user styles, which are entered in the middle of the document after these instructions:
If you put your declarations in these commented-out instructions, your code will also be commented-out. I’ve seen that happen before, and the student came up to tell me that the template does not work. I’ve also seen students use the index.html page by itself. That also does not work. Keep the folder intact.
After the user styles there are a number of preset styles that can be called to perform a number of tasks. You want these to remain intact after your styles.
All you have to do is create your styles in this middle Primary Styles Author section. and ignore the rest of the style sheet if you do not understand what it does.
Where to put the HTML
Once again, ignore everything that you do not understand.
put the title of the page between the title tags:
<title></title>
Next enter a description of the page/site:
<meta name="description" content="">
Fill in the author:
<meta name="author" content="">
As long as you did not change this name of the style sheet, the default link should work.
<link rel="stylesheet" href="css/style.css">
Enter all of your HTML replacing the code below
Ignore everything else that you do not yet understand.
Hello world! This is HTML5 Boilerplate.
Google Analytics code is already in place. You already have an id if you signed up and followed the instructions . You need to replace “UA-XXXXX-X” with your account number. This way the page is tracked by google’s analytic software, and you can check up on who visits you, how long they stayed, which pages they navigated and more.
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
Turning a Single Page Into a Website
Work on the index file till you have made it just like your Photoshop comp / wireframe, with everything as you want it.
Include in this file a styled navigation with links to all of the files that you wish to target. Examples are about.html or bio.html, drawing.html, etc.
When you feel you have achieved this to the point of perfection, duplicate the index.html file and rename each copy to the appropriate page name that you specified in the navigation. This way the site is almost already build as soon as you finish the first page.
The Boilerplate is for Your Own Good
This is not much more complicated than before, as long as you can ignore some of the extra code.
Just know that your HTML5 and CSS3 will be more compatible with other browsers than if you did not use this template. That said, if anyone wants to learn this stuff, I recommend going through this boiler plate carefully, read the documentation, and follow all of the links, for you will learn a lot.
Adding Google Analytics and SEO
Follow the instructions in Google Analytics to get a google analytics account number. Place that number in the index.html file.
Building a standards compliant website with good content is best for search engine optimization. The problem many of you will face is that all your work is composed up of pictures. Search engines prefer words. Make sure that you describe your pictures will in accompanying text or use the alt tag to let the people who use search engines reach your pictures.
Three homework assignments to be finished by week 8.
No additional homework will be given.
previous homework needs to be completed.
Be ready to present your work in class by week 8.
Midterm:
Portfolio is to have a minimum of five pages, the landing page, three product pages and a bio page.
Navigation does not have to extend beyond five pages but it’s a good idea to plan and develop the entire online portfolio. Having your information architecture and navigation in place saves on revision time.
Implement the HTML5 Boilerplate, build the navigation and code the remaining design.
Start simple with a responsive wireframe that works on all three types of devices, from phones to large computer screens, before developing the details of your design.
Post the wireframe
Build Political Website
You are to be inspired by a political cause and built a five page website highlighting some aspect of the political cause if your choice as a practice run to see how quickly you can build a convincing website. Use available content by searching the web. This is only an exercise in building a website, please take pictures and copy from other sources. State your case, back it up with facts and tell the world what it’s about.
The New School celebrated its centennial last Semester and I submitted a proposal and got two lectures happening, but that has passed. This semester they have the Climate Emergency Teach-In on March 2, a Monday, from 11:00 to 3:00. I will be there. Attend and do your website on the climate emergency.
Create a website highlighting what you learned and build a convincing argument. State your case, back it up with facts and tell the world what you are going to do about it. I do not expect you to write the material yourself. Google the information from whoever shares your options including copy, facts, and pictures.
The Website is due in Two Weeks along with the portfolio website. It should be built with the new flex box and css grid and use the new typographic tools we went over in class.
Typography Exersize: Watch the the Don’t be Afraid video on Web Typography by Jessica Hische and Russ Maschmeyer. It is only 11 minutes long. The first half explains font-family, font-weight, font-size, text-transform, letter-spacing, line-height and text-align. The second half goes through the creation of a menu in 11 steps with a link to the the starting file along with the steps mentioned in the video so you can follow along: step 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and the final step 11. Take a look at the finished file. You’ll learn a lot and it is what I want your typography to look like, so please take the time to watch the video!
Know the rules in design and typography. Know when to break them. Be inspired to push or break the rules for typography in web design. David Carson on the end of print with William S. Burroughs reading from his own texts.
David Carson: The End of PRINT
David Carson speaking about his own work.
David Carson: Ted Talk
Chose a poem or statement or use the Cummings Poem l(a
“l(a” is a poem by E. E. Cummings. It is the first poem in his 1958 collection 95 Poems
“l(a” is arranged vertically in groups of one to five letters.
l(a
le
af
fa
ll
s)
one
l
iness
When the text is laid out horizontally, it either reads as l(a leaf falls)oneliness —in other words, a leaf fallsinserted between the first two letters of loneliness– or l(a le af fa ll s) one l iness, with a le af fa ll s between a l and one.
In-class Demo for both 9:00 and 12:00 classes. You can download them as well.
The design of the demo was directed by students, exploring problem solving as we went along.
Download HTML5 Boilerplate
You are given a choice, to download the standard HTML5 Boilerplate, which is what we will do in class.
The other option is to get a custom build template.
If you decide on customizing it, get the Bootstrap version. Read all about it. Bootstrap has many goodies built in to make your site will look and work professionally.
Follow the instructions in Google Analytics to get a google analytics account number. Place that number in the index.html file.
Building a standards compliant website with good content is best for search engine optimization. The problem many of you will face is that all your work is composed up of pictures. Search engines prefer words. Make sure that you describe your pictures will in accompanying text or use the alt tag to let the people who use search engines reach your pictures.
Technical Note
The HTML5 Boilerplate is shipped with a lot of things to make life better, but one thing trips the school server, and you need to take it out.
You will not see this file on your computer, but once you have uploaded the files to the school server, you will see a file called “.htaccess.” This file contains the following line that needs to be taken out:
# ----------------------------------------------------------------------
# Prevent 404 errors for non-existing redirected folders
# ----------------------------------------------------------------------
# without -MultiViews, Apache will give a 404 for a rewrite if a folder of the
# same name does not exist.
# webmasterworld.com/apache/3808792.htm
Options -MultiViews
This trips up the server, and you will see a page for error 500.
Server error!
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.
If you think this is a server error, please contact the webmaster.
Error 500
a.parsons.edu
Apache/2.2.3 (CentOS)
Flex Box display: flex; makes it easy to distribute elements within a containing element, — either as a row or as a column. Flex box aligns both the elements and the space within a parent container. This happens even when the parent ’ or children’s size are unknown or dynamic. The child items’ width, height, and order can be set to best fill the space that they take up.
Flexbox is good at taking a bunch of different sized things, and returning the most readable layout for those things. It avoids squishing a big thing into a small column, and leaving big gaps round a small thing. If you want to control the size of your columns precisely, use Grid.
Flex box Terminology
The various directions and sizing terms as applied to a row flex container. from w3.org. To be direction agnostic, the terms start and end are used.
Initiate the parent as flex container. The container can be a block display: flex;or inline display: inline-flex .
Only the direct children of the parent flex container are effected.
Flex Direction
The flex container has a main axis, either horizontal or vertical, the primary direction along with flex items are laid out.
Use flex-direction: horizontal; or flex-direction: horizontal-reverse; to specify the main direction as horizontal, from left to right or right to left.
Use flex-direction: vertical; or flex-direction: vertical-reverse; to specify the main direction as vertical, from left to right or right to left.
The numbers in the demo reverse when the direction is reversed.
Justify Content
Content is justified by setting the justify-content: property to the following values: flex-start, center, flex-end, space-between and space-around.
The values space between collapses the padding between the flex container and the first and last item while space-around adds some padding.
Flex Box Demo
CSS Code View
Live Demo
1
2
3
Using Margin: Auto
Using margin: auto creates automatic space that allows for useful relationships, like in a menu along the main axis, where some menu items are on the left, and others are on the left. Insert a margin: auto and the content splits to the end of the main axis leading a gap in the middle.
Activate the demo by removing the /* from the CSS rule below that targets the third column of the demo above and witness the power of margin: auto to push children around in the flex box parent. Change the target to the second or first columns to see the content rearrange.
CSS Code View
Flex-Wrap
Flex does not automatically wrap its children into multiple lines within the container. If there are too many flex-items, they will extend beyond the flex container’s boundary. Wrapping the flex items will wrap them into multiple lines below (or above with wrap-reverse). The demonstration below uses the setting from the previous demo.
Cross Axis Flex Item Align
The cross axis is perpendicular to the main axis. Flex items can be aligned at the start, center or end, or can span the axis.
CSS Code View
Live Demo
content
more
content
less
content
enough
content
Flexbox Item (children)
The flexbox items (children) are all the elements that are direct children of the flexbox container, and they can be controlled independently from the flexbox container controls. It is possible to align, order, and determine the proportional size of any of the flex items. This has been made into a separate module that also works for CSS Grid item control.
Order
The display order of the flex items follows the order in which the HTML is written. That can be changed by specifying how many items forward or backward the flex item is to move.
Align
Align flex item can be applied to any element. Here the third flex-item is flex-end , where the others are flex-start . Put them all on stretch, and you have the perfect equally long shaded columns. That is the aim of the Holy Grail Layout below.
Proportion
Width of the boxes can be determined proportionally and is specified for each flex-item by the flexproperty.
CSS Code View
Live Demo
1
Different amount of text in these boxes shows how the cross-axis align function works. There is control for how the boxes align or stretch to all be the same hight no matter how little or how much content. The flex value for this box is 3. Remove the align self and set the align items to stretch and all the flex items will span the cross axis.
2
Box 2 has not as much text as box 1 but more than box 3. The flex value for this box is 2 and order is -1 which places it before box 1.
3
Flex value for box 3 is 1 and it’s self-aligned.
Flex Grow, Shrink, and Basis
Rather than specify a fixed ratio between the flex elements, the proportion can be given parameters by the Flex Layout Algorithm and the fit is dynamically determined. This is because the default is flex-shrink: 1, meaning that each element will shrink such that all elements fit in the parent. Change the default value to 0 and all the magic of flexbox disappears, as the flex items will grow beyond the parent. Flexbox is set up to automatically fit the content within the parent. The fit of the flex-items to the remaining space, or lack of space is determined against a reference basis width using grow, shrink and basis controls.
Grow
The Flex layout Algorithm defines the ability for a flex item to grow, starting from the basis number, if the content requires it (when the parent’s width expands). It calculates the proportion for each flex item inside the flex container. Flex growth is the amount a flex item can grow in proportion to the other flex items. If all items have flex-grow set to 1, every child will have an equal potential to expand if their content requires it. If one of the children has a value of 2, that child would take up twice the growth as the others.
Shrink
Flex-shrink does the opposite, with a higher number defining how much greater the shrinkage of an item (when the parent’s width shrinks). In the following example, watch what happens when you cut the width of the parent flex box by 50%. The box with the highest flex-shrink number shrinks the most.
Basis
Flex-basis is the starting or default size of an element before the remaining space (shrink or expand) is distributed. The default is auto. Any value for width or height properties are accepted. If using 0 use units to avoid being interpreted as a flexibility.
settings
The flex property may use up to three values.
If there is only one value a number without units is interpreted as flex-grow or with a unit as flex-basis. You can also use the keywords none, auto or initial.
If there are two values the first value must be a number without units and is flex-grow. If the second number is without units it is flex-shrink or if it has units it is flex-basis.
If there are three values the first is flex-grow, the second is flex-shrink, both without units, and the third has units and is the flex-basis or the value auto.
In auto the item is sized according to its width and height properties, but grows to absorb any extra free space in the flex container, and shrinks to its minimum size to fit the container. Auto is flex: 1 1 auto.
Initial is the default value. The item is sized according to its width and height properties. It shrinks to its minimum size to fit the container, but does not grow to absorb any extra free space in the flex container. Initial is flex: 0 1 auto.
In none the item is sized according to its width and height properties. It is fully inflexible: it neither shrinks nor grows in relation to the flex container. None is flex: 0 0 auto.
By default flex items don’t shrink below their minimum content size. To change this, set the item’s min-width or min-height.
The demo evaluates the content and proportions the boxes automatically according to content shrink from 50% and grow to 150%. Flex box item number, the red box, will expand and shrink more than the others.
CSS Code View
Live Demo
Different amount of texts in these boxes shows how the cross-axis align function works as there is control of how the boxes align or stretch to all be the same hight no matter how little content. The flex value for this box is 1 0 8rem.
When there is not much text but more than in the last row. The flex value for this box is 1 0 6rem.
The flex value for this box is 1.5 0 5rem.
Page Layout Demonstration
Once upon a time, a very long time ago, there was a Holy Grail Layout with a three column body, a header and footer. This was accomplished without tables. This was long before mobile changed everything so the layout was not even responsive. How the times have changed. A responsive Holly Grail, so when the viewport shrinks the columns stack.
CSS layout strategies. Block, inline, relative and absolute positioning, floats and floating layouts and CSS3 Flex property and grids. Activity: Begin translating Photoshop Comps into HTML/CSS using multiple layout strategies.
Using different layout strategies build your portfolio following your Photoshop comp. Read chapter 11. Due: The following week. First Quarter Assessment: Have your landing page, first two assignments and portfolio up.
Questions from Last Weeks Class or Homework?
Goals
The goals of this unit are to:
Understand how the native document flow works, and how to alter the normal flow for layout purposes.
Effectively use absolute positioning, float, and display properties.
Investigate flex and gid.
Be comfortable applying various options to solve the problems layout presents.
Materials
Additional materials for this unit can be found by following these links (52 pages):
Cheat Sheets that list all of the different HTML5 and CSS3 tags you can use. Print them out, use them. Explore and get to know them. You can use these during the quiz next week:
HTML5 Cheat Sheet all of the different tags and the attributes they can have.
CSS3 Cheat Sheet all of the different properties and all possible values or value types they take.
CSS Tricks Almanac A reference guide to the many features of CSS from CSS-Tricks .
Install these Plug-ins if you use Firefox or Chrome. They will facilitate your web development. Do not forget to activate the Show Developer menu in menu bar under the Advanced tab in Safari’s Preferences. Detailed help pages are available for Safari Web Developer are available.
There are many frameworks that allow you to build your websites using preexisting CSS. They arose because layout in CSS is neither intuitive nor easy, and go from simple grids to complete font-end frameworks.
There are many services that allow you to build your own websites, and you can use the HTML and CSS skills you learn here to modify them. This can give you the best of both worlds, for you can use their platform and templates but modified so that they look unique in ways that goes beyond template options.
build your own
WordPress Build your own with lots of templates to choose from.
Or use a pre-made platform. Note that there are limitations imposed, like Wix depends on absolute positioning to give it flexibility in designing the site but that end up curtailing the flexibility in other ways.
Tumbler Customize the experience with HTML and CSS.
Lynda.com is a resource for instructional videos. She has been at it for a long time, and there are a lot of videos on HTML (34) and CSS (36). They can be a great resource, and in addition to my performance in class, the class notes and portal, the good and the web itself, there are no reason for not knowing. That said, there are too many titles to intuitively know what to do, and this section will appear whenever there are supporting videos at Lynda.com
CSS (Cascading Style Sheets) describes the rendering of documents on various media. When textual documents (e.g., HTML) are laid out on visual media (e.g., screen or print), CSS models the document as a hierarchy of boxes containing words, lines, paragraphs, tables, etc. each with properties such as size, color and font.
This module describes the basic types of boxes, with their padding and margin, and the normal “flow” (i.e., the sequence of blocks of text with margins in-between). It also defines “floating” boxes but other kinds of layout, such as tables, absolute positioning, ruby annotations, grid layouts, columns and numbered pages, are described by other modules. Also, the layout of text inside each line (including the handling of left-to-right and right-to-left scripts) is defined elsewhere.
Boxes may contain either horizontal or vertical lines of text. Boxes of different orientations may be mixed in one flow. (This is a level 3 feature.)
This CSS3 module defines properties for text manipulation and specifies their processing model. It covers line breaking, justification and alignment, white space handling, text decoration and text transformation.
Floats. In the float model, a box is first laid out according to the normal flow, then taken out of the flow and shifted to the left or right as far as possible. Content may flow along the side of a float.
Absolute positioning. In the absolute positioning model, a box is removed from the normal flow entirely (it has no impact on later siblings) and assigned a position with respect to a containing block.
A float is a box that is shifted to the left or right on the current line. The most interesting characteristic of a float (or “floating” box) is that content may flow along its side (or be prohibited from doing so by the ‘clear’ property). Content flows down the right side of a left-floated box and down the left side of a right-floated box. The following is a (non-normative) introduction to float positioning and content flow; the exact rules governing float positioning are given in the next section.
A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float. If there is a line box, the top of the floated box is aligned with the top of the current line box.
If there isn’t enough horizontal room for the float, it is shifted downward until either it fits or there are no more floats present.
Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float didn’t exist. However, line boxes created next to the float are shortened to make room for the margin box of the float. If a shortened line box is too small to contain any further content, then it is shifted downward until either it fits or there are no more floats present. Any content in the current line before a floated box is re-flowed in the first available line on the other side of the float. In other words, if inline boxes are placed on the line before a left float is encountered that fits in the remaining line box space, the left float is placed on that line, aligned with the top of the line box, and then the inline boxes already on the line are moved accordingly to the right of the float (the right being the other side of the left float) and vice versa for rtl and right floats.
(This is a more advanced development of floats to exploit their wide usage in layout. It is one of the layout strategies coming out of the W3.org) CSS Floats and Positioning Level 3 allows authors to have text and other inline content wrap around specified elements, thereby allowing for the creation of more intricate layouts than is currently possible with existing CSS floaters. Specifically, CSS 3 Floats, also known as “positioned floats”, can be absolutely positioned on a web document, while still affecting the document flow. Authors can individually specify whether intersected block elements surrounding a positioned float (e.g. paragraphs, divs, etc.) overlap with the positioned float, and if so how they overlap with it. Positioned float can also be styled with a wrap-shape property, which specifies both how text within the positioned float is laid out and how content outside the positioned float wraps around the positioned float. It is also possible to define a shape based on transparency values within an image.
A typographic grid is a two-dimensional structure made up of a series of intersecting vertical and horizontal axes used to structure content. The grid serves as an armature on which a designer can organize text and images in a rational, easy to absorb manner.
Watch the last video in the Don’t Fear the Internet series on traditional layout. These are basic but necessary layout tools, and the web has gone well beyond this, but if you are not 100% sure, it is good to watch the whole series.
Open up the worksheet, right-click and show page source. Select all. Copy and paste into a blank Brackets document. Save as quiz-2.html and follow instructions. You will be writing CSS. Do not change the HTML.
Implement @media break points for SmartPhone and tablet if you designed your website for your laptop screen. @media go below your large screen styles. Note that if you designed your website for the smart phone first, you create tablet and large screen @media queries.
Apply @media queries to the section element of the portfolio that you marked up last week, and change the border or background color to test out if the @media queries work. If they work, target the next biggest element, like header, to make sure it also changes. Do so for the navigation, main article, and footer elements, and create a wireframe.
Tweak the elements so they show correctly for each media. The wireframe should update to best display the contents on each medium. When the wireframe works smoothly, it and link it to the portal.
Fill out each part of the wireframe with pictures and text as rendered in step 8.
Heads Up
In 2018 The New School spent the week on DISRUPT CLIMATE INJUSTICE. Create a five page website highlighting one or another aspect of climate change and build a convincing website. State your case, back it up with facts and tell the world what you are going to do about it. I do not expect you to write so much as express your opinion with the facts and pictures that you gather.
This semester the school has the Climate Emergency Teach-In on March 2, Monday, from 11:00 to 3:00. I will be there. One possibility is to attend and do your website on the climate emergency teach-in.
Grading Criteria
I am looking to see how well you can juggle these boxes, and it takes a while to move them around through the document flow.
It is a lot like when you were a kid, playing with blocks, only here that world is upside-down, as you start on top, and build your way down. You will get the hang of it by doing it.
Validating your work often is a good technique to keep you on the strait and narrow path. Once you get better, you need not check so often but right now, check every few lines of code.
I will be grading you on levels of confidence, consistency, creativity, innovation, precision, accuracy, efficiency and the ingenuity as you manipulate the elements in the document flow to build your page.
Going over how everything works does not mean you understand it. This demonstration will help you understand how to lay out a page. It explains step by step how to lay out a page using no floats, and then explains how to use floats to create the same page. It assumes familiarity with the information contained in these other pages in this section, and with the previous sections:
In the first homework assignment you marked up content using heads <h1>–<h6> and paragraphs <p>, added links <a> and images<img>, and grouped certain content together using the generic <div> or the more semantic HTML5 tags like <header>, <nav>, <section>, <article>, <figure> and <figcaption>.
At this time you did not nest too many tags inside of other tags, but know that every tag you created was already nested as a child of the body tag. As you develop the layout, you will increasingly nest tags inside of one another, usually to define and group an area of the layout, like the header, right column, main content, navigation or footer.
When you look at the first assignment, you see the browser’s default style at work. The content vertically lines up, one below another, while the text flows left to right.
To better understand this structure, change the embedded style included in the HTML5 template, which looks like this:
<style type="text/css">
.example {
}
</style>
To an embedded style that puts an outline or border on all elements, like this:
A red outline is put on the elements that are displayed according to the block mode and a green border is put on the elements that are displayed according to the inline mode.
Each element of the assignment now has an outline or border.
Take a moment and explore the way the red outlined block elements stack below one another. Each element’s width extends all the way out to the parent by default.
Inline elements with green borders styles the content (type) in block elements, flowing from insertion point to the end of the box. It then start over on the next line. Not all languages flow horizontally or left to right, though english does, so we can say that type starts left and flows horizontally.
The other display modes besides block and inline are tables, which are not to be used for layout purposes, and the absolute display mode, which completely removes elements from the document flow.
Styling the Elements
I use an embedded style sheet for this example, but you should use an external style sheet. Because the rules act at a distance, you need selectors placed in front of the rules to target the elements.
The best selectors to use are type selectors, that select the element by its type, i.e. p for selecting all paragraphs. You can combine them to get more specific, like article div p, which targets only those paragraphs in the div in the article. If that doesn’t work, you can use the pseudo class selectors like :nth-child(N) or use class selectors if you want to target certain elements, but avoid using ids, as they are much stronger than classes and tend to dominate the cascade hierarchy.
Select each of the elements in the document and change the background color to know that you have successfully targeted that element with a CSS rule.
Altering the Default Layout Order
The block elements are like a child stacking playing blocks one on top of the other, only upside down, starting from the top with one box below the other. This is the normal document flow mode, and it is similar to how a word processor works. The difficulty of laying out a document using the normal document flow is that you have to build your way to every part of the document. The benefit is that if one thing changes, everything else adapts, if it’s done right.
Most Design students layout their documents using Indesign (Illustrator, or even Photoshop). The activity of creating and moving design elements where you want them is what layout is all about. Forget the normal document flow! The absolute display mode is similar to the layout mode of Indesign, but be careful. The web is a much more flexible environment than print, and the layout has to accommodate that. You need to be judicious in the way you use absolute positioning.
The flexibility of the web as a medium means the layout is much more likely to be determined by the normal document flow, whose default behavior we’ve just looked at, than the rigid absolute positioning used for print. This means that you can’t just pick up any item and move it to where it looks best. Instead, you have to figure out how to best position it where you want, using all of the previous elements in the normal document flow. This is possible with planning. That’s why the emphasis on the creative process with thumbnails, mood boards, wireframes and a Photoshop comp before starting to code the layout.
Yes, there is not much spontaneity in coding the layout, but then, there is little spontaneity in prepping an Indesign document for print. The creativity and spontaneity of web design happens in the early planning stages. After that it’s mostly creative problem solving as you try to execute the layout. You are ahead of the game if you can see this as a puzzle to be solved.
Homework Assignment Not Using Floats
The following step by step tutorial is meant to explain the homework assignment and uses the techniques explained in the Beyond Floats article.
You start by opening up an HTML5 template and pasting into a blank document. Paste in the CSS reset at the beginning of the style tags in the head. This prepares your document for coding.
Setting Up the Page
While we want the page to center in the window, if the window becomes too wide, it looks kind of funny, so we put in a wrapper div with a max-width: 1300px to keep the page from centering when the window gets wider than that. It’s tradition to call that first div “wrapper,” though you could just as easily select it with the selector body>div, which selects any immediate child div tags of the body tag.
<div class="wrapper">
with the style being:
.wrapper {
max-width: 1300px;
}
If some of your pages have enough content on them that they force a scroll bar, the entire content shifts 8 pixels to the left. The web site then moves to the left as you move from a page that does not require a scroll bar to one that does and vice versa. If that annoys you, force a vertical scroll bar to appear by making the page 1 pixel more than the height of the window:
html {
min-height: 100%;
margin-bottom: 1px;
}
This page is long enough to force a vertical scroll bar, so it’s not an issue, but if you were to use this technique on your web site, it very well might be an issue.
Next comes section tag to create the actual page for us. We want to center the page inside of the wrapper div, so we need to specify its width (960px) and set the left and right margins to auto. I set the background color for the page to middle grey, create a margin on top to push the header element down 70px, and finally, set the positioning to relative, so that any absolute positioning will be in relation to the page and not the body.
The first element is the header. This is the bar with the name and picture on it. The position of the bar is taken care of by the padding-top (90px) of the section element. The width is a little tricky. I want to put a shadow on the header element (shadow 1), but do not want the shadow to bleed out over the right edge of the page. The solution is to shorten the header to just 930px so that the shadow looks good. Had I not restricted the width of the element it would have expand to 100% of the parent window, and the shadow would have fallen outside of the header, and the page as well.
Nested inside the header is div that is given a width (848px) plus padding-left (112px) that equals 960px, the same width as the page. Because the div comes after the header in the way the computer reads the page, it is drawn on top. The HTML5 code for the header is:
Since the vertical relation between boxes is pretty much taken care of, most of the strategies concern how to place boxes horizontally next to one another. The relation between name and the picture provide us with an opportunity for using one of these strategies. I could choose to float the name to the left. That would put the picture on the right next to the name. I could also change the display from the block to inline, and vertically center the two, but I use absolute positioning instead.
The h1 element falls into place because of the padding added to the parent. As you can see, the header div has 20px of padding added to the top and 120px of padding added to the left padding: 20px 0 0 112px;.
I then apply absolute positioning to the figure that holds the picture. The figure no longer occupies any space in the document flow and floats above that layer by default. I’m free to move the figure up 70px, which is specified as top: −70px, and either 640px to the left or 40px to the right of the parent element. (640px + 280px (width of the figure) + 40px = 960px). It does not matter whether I go from the left or right side of the parent element since its width is fixed.
I’ll also use absolute positioning to horizontally layout the aside, and nav elements. The potential problem this creates is a lack of flexibility, so I have to be careful, and be prepared to adjust things manually if there are changes. Some problems are avoided by using it only for horizontal placement, but I still need to be careful. Additional links would require a larger image or more space to push down the text box, for example, otherwise the navigation would overlap. This is the HTML with the content removed:
The nav is positioned absolutely to the right (0px) with a top margin of 130px and a right margin of 80px. This removes it from the document flow and positions it below the picture. Adding padding moves it down and over to the left, correctly placing it according to the comp. I could just as well have positioned it from the left side of the document. Flexibility is increased by not invoking absolute positioning for vertical positioning (by using top:), leaving that up to the document flow. That would have locked in the vertical position of the navigation to the page, causing a problem if I were to change the height of the header.
The navigation is targeted by three classes, first the anchor itself, which is made to act like a block so it will act like a box, the second is a:hover, which changes the style when you roll over, and lastly a:active, which changes the style when you click on the button.
Though the aside has no width, the figure that make up its content is 200px in total (160px for the figure and 40px for the left margin). Giving the article a left margin of 200px and a padding of 40px creates a place in the layout for the article.
The article content has a width of 960px −80px −200px, or 680px. Because the navigation is absolutely placed you have be aware of keeping content out of its way. This is the downside of absolute positioning, but it’s taken care of in this layout by the large picture in the figure tag.
There is no need to go over absolute positioning once again, and so I use table-cell to position the columns. The enclosing div has a 40px margin on top that separates it from the figure above and a background of #ccc. The two columns are layer out horizontally by divs whose display has been changed from the default block to table-cell. Here is the CSS:
The headline on the navigation and the article use relative positioning, but with a trick. Relative positioning leaves a space in the document flow. By creating a negative margin, its possible to erase that space, which makes it possible to insert an element in the document flow without it taking up its normal space. This is the case with the headline, which is located above the insertion point by 60px. I set it for the navigation, but that turned out to be slightly off for the column, so I had to adjust that with two declarations. This is a useful trick if you want to include an aside that stays with the main text while you are editing it, for example.
Floats are used to put boxes side by side which does not happen in either the header or the footer, so we only change everything in between. The page is divided into three columns: the aside, the article and the nav and the main content has two columns. Relative positioning is no longer need and is removed from the section and it gets overflow: auto; instead, to force the parent to recognize its floated children, a trick discussed in floating Layouts.
If you look at the HTML, you can see a few changes. The nav is now inside of the article and the h2 is now before the first column in the div.
The aside and the article are floated left. This places the article to the right of the aside. There is no need for the 200px left margin on the article. As there is no need to change the figure in the aside and article, I do not list them in the CSS below:
The nav and the picture are children of the article. Floating the nav to the right places the picture to the left of the article. The margins and padding of the nav are updated to place it in the same place.
As long as the combined total width does not exceed the width of the containers, the elements will float next to one another: 200px for the aside, the plus the 550px of the article (260px for the figure (plus 80px margin) and 120px (plus 50px padding and 40px margin) for the nav) equals 750px, far less than the 960px of the section.
The div that follows the is given a clear: right, forcing it to position itself under the nav. That way it will be responsive and move down if additional links are added. This was not possible using the absolute positioning method. Chances are, however, that the layout would require fixing if that were to happen, so the difference is not so great from the work required to facilitate the absolutely positioned layout.
The Challenge with Floats
I also want to float the two columns, but ran into a problem with the h2 header. It got clipped by the floated column, but when I moved it to the div, it still got cut off because of the overflow: auto;. For that reason, an older solution to the problem was used to force the parent to recognize the floated children, using the pseudo object div:after to create an object after the last column that can be cleared using CSS alone. Clearing the last child forces the parent to recognize all of the children. Here is the CSS:
What this pseudo element does is place a period after the article div. It then forces the period to display like a block element instead of the inline element that it is, and gives it height: 0; so it does not actually change the document flow. It then clears the floating children, which is the reason we are doing all of this. That is another way that the parent element can recognize its children. The final declaration makes sure that the period’s visibility remains hidden. OK, that’s a lot to comprehend for a technique that has been superseded by the overflow: auto; method, but its good to know that it’s still useful when overflow does not work. The rest of the CSS looks like this:
The first column is floated to the left and the second column appears to the right of it. All that’s left to do is to align the h2 header for both the nav and the div. Because both of them are in the selector of the h2 in the div selector has to be further specified as article div h2{}.
Learning the traditional layout modes developed for CSS2.1.1 offers several advantages. Firstly, they provide a structured approach, ensuring that you begin with a solid foundation. Secondly, they serve as essential tools for securing the layout through manual or mechanical means. While newer layout strategies automate many aspects, they do not replace these fundamental tools but rather enhance their capabilities, making responsible layout easier and more automated. Moreover, many newer CSS features aim to expand the power of CSS to automate layout, allowing designers to maintain better control over changes in size. Additionally, some features facilitate data dumps, as designing for variable content with the same parameters becomes increasingly challenging.
Layout in CSS 2.1.1
CSS 2.1 has four layout modes that can be strategically used, in addition to the ubiquitous floats. They are block layout, designed for laying out documents, inline layout, designed for laying out text, table layout, designed for laying out data in tabular format and positioned layout, designed for very explicit positioning without much regard for other elements in the document. Floats were originally applied to pictures so that they could be floated to the right or left and text would wrap around them. Both tables and floats have been used by web designers to create layouts for which they were never intended. Their use for layout is no longer necessary. Tables were replaced by floats in 2007 and floats were replaced by Flex and Grid in 2017. CSS layout has been transformed by the release of multicolumn, flexbox and grid. These will be discussed separately.
Many layouts require multiple strategies at once. This means understanding all of the strategies is the only strategy. If each strategy can be considered a tool, you need all of the tools to build a responsible web page.
The Box Model
The box model is central to understanding how to do layout with CSS. Every element is a content box with specific properties; padding, border and margin, in addition to all the other layout properties, like position, width, height, display, and so on. Elements (or boxes) grow to fit the content.
Default Behavior
The default setting for the box properties is no height and width set at 100% of the parent box. By default, all children boxes are the same width as their parent. The body element is parent to all elements (boxes) in the viewport, and is by default the width of the viewport. The viewport is the width of the window, or the device.
Default behavior sizes the box with the content. Padding, border and margins are in addition to the specified height and width. The actual size of the box in the layout is the content plus the borders and padding. A box that is 400px wide, with 20 px padding, and 10 px borders would take up 460 pixels.
Negative margins can be used to subtract from the space that the content takes up in the document flow. In the demo below, if the content is height: 300px, and has a margin-bottom: -150px, the next element down will start midway the box, because the negative margin does not effect the size of the content. It also becomes clear that elements that come after are positioned above elements that come before. Change the second box’s top and bottom margins to -200px auto 0; and the second box move up 200 points over the first box.
Vertical margins collapse. Horizontal margins do not collapse. If the horizontal margin is 5px for both boxes, expect the space between the boxes to be 10px. But with vertical margins, if both were 5px, the space would be 5px, because the margins have collapsed. The margin collapses to whichever is the larger margin.
CSS 3 introduced the box-sizing property allowing box width to include the padding and borders. CSS Tricks has a nice history of how it ended up the way it is. It’s often applied to the entire page with the universal selector: *, *::before, *::after { box-sizing: border-box;}. You can toggle the box-sizing on and off in the demo or change it to content-box, the default, or padding-box:
Box Model Interactive
CSS Code View
BOX 1: The margin is set for 20px auto, meaning that the box has 20 pixels of margin on top and bottom, and the left and right margins are automatically adjusted to center the box, possible only because the box has a declared width
BOX 2: Though both boxes have a 20px margin, that margin collapses between the boxes.The smaller margin collapses into the larger margin.
The Layout Modes of CSS 2.1.1
The layout modes determine the layout of boxes in the document flow. Boxes act either as block layout, like inline layout, like table layout or like positioned layout in which absolute and fixed positioning , which disregards the document flow.
The best analogy of the document flow to the flow of a word processor, which starts at the top of the document and proceeds downward. All of the content is tethered to the top of the page. This document flow is composed of blocks that often contain inline content. Inline content is letters or words, pictures, links, etc. They make up the content of the block element they are in, and the block element will be as wide as the parent, and grow vertically to hold all of the content.
Contrast the document flow for a webpage with the document flow of programs like Illustrator or InDesign, programs made for print. In these programs, the last thing you want is for something to move. These programs are designed to provide freedom in placing a box anywhere on the page. Each box can initiate its own internal inline flow, but the box itself is not connected to the document flow, because there is no document flow. Instead, the place of each element in InDesign or Illustrator is determined by its x and y values, and its width and height.
Absolute or fixed positioning act similar to laying out designs in Illustrator or InDesign, but don’t try to use them as the foundation for your layout, because it will not be friendly to changes in viewport sizes. You can use them within the layout, once the foundation has been established. Elements are taken out of the document flow and no longer relate to one another.
Tables, the forth layout mode, are in their own world, and wile great for tabular data, should not be used for layout purposes, as that violates the separation of church and state, I mean, form and content.
Block Display
The block layout mode displays the boxes just described by the box model, in default configuration, vertically , coming one after another down the page in the direction of the document flow. Each box, by default, is 100% the width of its parent. Even if a box is not 100% the width of its parent, block elements still start on a new line, by default, starting at the top left corner of the <body> tag. Some HTML elements follow the block model by default, like headers <h1>, paragraphs <p> and list items<li>, and the generic block element, the <div>, though as we will see, their display quality can be changed to inline or table modes using the display property.
Inline Display
Inline tags enclose inline content elements. By convention and for Most of the WOrld’s languages, inline content flows from left to right, and top to bottom, but this can be changed for languages that do not follow the convention. Some inline content is replaced, but most is not. A character is a non-replaced inline element, but the picture element is replaced by the picture. Box properties like margins, padding and border properties are applied differently to these elements.
Both of these inline elements flow horizontally, one after one, till they reach the width of the containing box. The line then returns to the next line, just like this text. Inline flow, unlike the document flow, is language specific. The English language inline flow goes from left to right, and top to bottom. Japanese language inline flow goes from top to bottom, and right to left.
Elements whose default display is inline are the <img> tag, the Hyperlink <a> tag and the emphasis<strong>. The generic inline element is <span>, and you can use it to select any number of characters within the same parent container. The default inline display can be changed to block or table using the display property.
Tables
Tables themselves by default act like block elements but the layout mode of the table is different from the document flow. They used to be used for layout in the early days by programs like Dreamweaver created but they are not to be used for layout purposes anymore. Did I already say that?
The following example provides both the HTML used to build the table and the CSS used to style it. I have included the HTML code so that you can see their structure. The basic structure is a <table> element followed by a table row <tr>element in which table data <td> elements make up the columns. It is possible to nest tables, shown here by nesting the same table in two of the table data cells.
If you want to style the table, its best to create as many hooks in it as possible, and this table is loaded up with column descriptions, a table header, a table footer and multiple table bodies, all used in styling the table. The code and an explanation of how the table layout works is reproduced below:
CSS Code View
The Caption Holds the Title of the Table
Head 1
Head 2
Head 3
table data
table data
table data
table data
table data
table data
table data
table data
table data
table data
table data
table data
table data
table data
table data
1
2
3
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
Footer
table data
1
2
3
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
td
Footer
table data
table data
table data
table data
table data
table data
The Footer is a Place for Information About the Table.
<table id="table">
<caption>The Caption Holds the Title of the Table
</caption>
<col><col><col>
<thead>
<tr><th>Head 1</th><th>Head 2</th><th>Head 3</th></tr>
</thead>
<tbody>
<tr> <td> table data </td> <td> table data </td> <td> table data </td></tr>
<tr> <td> table data </td> <td> table data </td> <td> table data </td></tr>
<tr> <td> table data </td> <td> table data </td> <td> table data </td></tr>
<tr> <td> table data </td> <td> table data </td> <td> table data </td></tr>
</tbody>
<tbody>
<tr> <td> table data </td> <td> table data </td> <td> table data </td></tr>
<tr> <td> TABLE </td> <td> table data </td> <td> TABLE </td></tr>
<tr> <td> table data </td> <td> table data </td> <td> table data </td></tr>
<tr> <td> table data </td> <td> table data </td> <td> table data </td></tr>
</tbody>
<tfoot>
<tr><td colspan="3">
The Footer is a Place for Information About the Table.
</td></tr>
</tfoot>
</table>
For demonstration purposes, I included the table within itself, which is just a repeat of the code placed in a table data. The ability to put tables inside of tables for layout purposes was much abused in the early days of the web.
The HTML code for the table can be divided into parts, and each can be styled separately. There are table headings, footers, data cells and captions and rows, all of which can be styled. The even and odd table rows are styled using pseudo selectors. If you look at the code, you can see that the table caption comes first, then the table header, two table bodies that contain the table rows and the table data cells and finally a table footer. The row tags allow the three rows to be styled individually, though that too could be handled by pseudo selectors.
Positioning the Document Flow
All objects can be positioned in (or out of) the document flow, which stacks the content together like building blocks in reverse of gravity. Starting from the top, the elements build their way down. W3.org calls this the visual formatting model. Think of these as tools to help you create layout.
Normal Flow
In the normal flow, boxes are like blocks that follow the document flow as they stack. Each of these boxes can hold other boxes, inline content, or both.
Boxes are described as stacked paragraphs blocks, whereas inline elements are said to be “distributed in lines”.
The display of boxes can be changed to inline elements and inline blocks, or when they are floated, and thee elements act just like inline content like a line of text. Pictures act like inline content items as well.
The default normal flow of the blocks is like a word-processor, in which each box takes up space in the document flow. Top and bottom margins collapse to the larger of the two margins as demonstrated above. Left and right margins do not collapse.
For centering elementsauto margins provide an equal amount of margin on both the left and right side of an element, as long as the width of the element is given. If this does not work, you probably forgot to give the element a width.
Relative Positioning
Relative positioning maintains the position and size of the element within the normal flow, and visually moves the element relative to its static location in the normal flow. The horizontal and vertical distance shifts the element relative to the position the box has in the normal flow. Specify positive or negative distance from the top, left, bottom or right edges. If the relative position distance is 0, there is no change from the static position.
Boxes can and will overlap. Use z-index to adjust which box is on top. In the demonstration, the z-index is 1, and the box sits on top of the following box, which is contrary to the actual flow, in which later elements would cover earlier elements. A z-index of 0 would bring back the normal document flow, the same as if there were no z-index, and a z-index of -1 would put the element under its parent element.
Relative positioning is also used to ground absolute position elements. The parent of an absolute positioned element needs relative positioning (with no need to change its relative position) to ground the absolute positioned element to the parent. If the absolute positioned element is not grounded, it will be positioned relative to the first relative positioned parent, or the body element. In the demonstration, the parent element <div id="norm"> has a position of relative flow. If one of the paragraphs were to be changed from relative to absolute positioning, it will go to the top of this demonstration with whatever offset values it has. Take this relative position away, and the absolute positioned element will end up at the top of the document.
Relative and Normal Position Interactive
CSS Code View
Normal Flow
Block elements are those that create a box that can contain inline content. Block elements expand to the width of the parent, and follow one another like paragraphs down the page.
The boxes determine the relation to adjacent boxes through margins, and determine the relation to child elements and inline content through padding. In between the margins and the padding is the border, which can be set to show or hide for each side.
Static Position
Static position is the same as the normal flow, which is similar to relative positioning if nothing is shifted. You can see that in these paragraphs: some have no position and take the normal flow by default, some have relative position, and some have the position of static.
Relative Flow
Relative flow is a subcategory of normal flow, for the element’s position still takes up place in the normal flow but it has been shifted in the top, right, bottom or left directions.
The previous box has z-index applied and covers this box. Set that element’s z-index to 0 or get rid of z-index and it box will cover this box. Set it to -1 and it will disappear behind the parent. This box does not have a property for z-index. Give it a property of 1 and it will cover the fixed menu element.
Absolute Positioning
Absolute positioning takes the element out of the document flow. Switch the relative position to absolute, and you will see it use the same offset in regard to the parent box. Turn off the relative position from the parent box, and the absolute box will jump to the top of the page.
Absolute Positioning
Absolute positioning is the forth layout mode, and it takes the box out of the normal document flow, except for a placeholder, the point of origin on which the absolute positioned box is aligned, and positions it in a layer above it in relation to the containing box’s coordinates, as long as that parent has been given a position in the document flow. If not, it continues on down the ancestry till it finds an element that has been given a position, or the body tag, which often happens, and which places the absolute value relative to the upper left hand corner of the window or viewport. To avoid this problem, remember to give the parent of the box you want to move absolutely a position: relative; without moving it from its place in the document flow.
There is an attraction for students to use absolute positioning as the main layout system since it follows the paradigm set up in print with programs like indesign. The problem is that the web is not like print, and such layouts quickly get into trouble. While it is fine to use absolute positioning for the very simplest of layouts, it breaks down for anything remotely more complicated, where it is a better idea to layout the document manipulating the document flow through margins, padding, floats and relative positioning.
These warnings aside, absolute positioning can be very useful in placing elements exactly where you need them, and can allow for some nifty layout calisthenics, as the demo shows, where objects are distributed by manipulating percentages in relation to the parent. If you change the position to fixed, the squares float in relation to the viewport. If you change the position to relative, and negate the object’s place in the normal document flow by adding negative margins, the objects will behave somewhat similar to the absolute positioned objects.
It is possible to manipulate elements like this because they can have more than one class as long as they are separated by a space: <div class="one box a">. Each box has three classes determining them: <div class="one box a"><p>1
</div>
Absolute Positioning Interactive
CSS Code View
Live Demo
1
2
3
4
5
6
7
8
9
Fixed Positioning
Fixed position is a subcategory of absolute positioning. The difference being that the container box is the viewport. The viewport is the window, so it is absolutely fixed to the window, regardless of the scrolling contents in the window. This can be used for menus like the one to the right, that stays in place while the user scrolls up and down the page. You can see this if you change the position of the boxes above to fixed, and they will float in the relation to the viewport.
Sticky Positioning
CSS Positioned Layout Module Level 3 Sticky position is a hybrid position that incorporates elements of relative, absolute, and fixed positioning to accomplish its effect. When scrolling a page, an element sticks to the top or bottom for as long as the parent container element is visible.
When an element is defined as sticky, the parent element is automatically defined as the sticky container. The parent is the maximum area that the sticky item can float in. In the demo, the header only floats in the container designated by the green box, and has a z-index:10; stacking order, so it remains on top. The footer of the second box is also sticky.
Sticky Positioning Interactive
CSS Code View
Live Demo
Title
Content
Title
Content
Z-Index Property
Once an element has been positioned, it’s overlap on the z-axis can be manipulated by the index property. This can be thought of in terms of having multiple layers, much like an Illustrator File. The normal flow happens at level 0, and you can put elements above and below the normal flow by giving them a number for −100 to 100.
Set the z-index of the following boxes to negative to read when using z-index can be useful. Play with the stacking order, and remember, the element you want to position in another layer other than the document flow has to be positioned first. Try giving the all the boxes a z-index of -3 and watch them move behind the text. Reverse the order of the boxes by changing the first box to -1, second to -2, third to -3 and the last box to -4.
Z-Index Property Interactive
CSS Code View
Live Demo
Box A:
Box B:
Box C:
Box D:
Making the z-index negative and watch the boxes go below the parent. Z-index can be especially useful if one element accidentally cover up a menu item, which is then no longer responds. By changing the z-index, you can move the menu above whatever is obstructing it.
Stacking Context
A stacking context is an element whose children can be ordered only relative to one another. Assigning the property z-index automatically creates a stacking context. As stacking contexts are not visually indicated there will be times when stacking contexts create confusion. It can happen, for example, that it becomes impossible to move one element on top of another using z-index despite astronomically high z-index values. As the z-index command does not work you may try to use !important to force it to work but to no avail. Once a stacking order is assigned to an element all its children become relative to each other and not relative to elements outside of the stacking order.
A number of other properties force stacking contexts because of the way CSS optimizes the way it renders a webpage. None of these properties are inherited but do pass on their effect to their children. These properties are opacity, transform, mix-blend-mode, perspective, isolation and position: fixed. The element and their children are flattened into a single layer to speed up rendering for browser efficiency. That makes it impossible to use z-index to layer something from outside the stacking context into any of those elements.
Display Property
The ability to change the display of an element is a very powerful feature of CSS, and its ability to function as a layout strategy has been overlooked during the time when floats reigned supreme as the Beyond Floats Article shows. It has since been updated to include flex and grid.
It is possible to change a block element to an inline element, to a list item to a table, table cell, etc. This is very useful for changing the basic behavior of an element exploited in the Beyond Floats Article.
Be aware that an inline object is content and does not have volume beyond the content box and requires the use of the inline-block value to change it to block behavior while remaining compatible with inline behavior.
Another important display values is display: none. That allows the element to be hidden from view till it is called up by a pseudo class like hover. This is one way to make CSS drop menus with multiple levels stay hidden till they are hovered over. No one here will build a website so complicated as to need such a menu though styling the navigation article demonstrates one. There is another property, visibility: hidden; or visibility: collapse;, that turns the visibility of objects on or off but that differs from display: none; in that the element still takes up room in the document flow.
Display Property Interactive
CSS Code View
Live Demo
Box A:
Box B:
Box C:
Box D:
Overflow Property
Unless otherwise specified, each box will span the entire width of the parent and accommodate whatever content. If you specify a width, text will just wrap within that width but if a replaced element, like a picture or a video file, is larger than the specified width, it could overflow the box boundaries, it could be clipped at the box boundaries or it could be accommodated by specifying horizontal overflow, in which case a scrollbar would provide access to the otherwise clipped content.
If you specify a height, its possible that both pictures and text could force the content out of the box. You can control this though the overflow property, which allows you to control whether or not content remains visible, hidden or if scroll bars appear to facilitate the extra content. You can also specify which axis overflows. Take away the comments from overflow-x: hidden; and you will see the horizontal scroll bar disappear.
If a web site has both short and long documents, in which case the vertical scroll bar can appear and disappear from page to page, with the result that the web site re-centers and the jump is both undesirable and quite noticeable. Telling the HTML element to always scroll in the y axis can solve that problem overflow-y: scroll.
Overflow Property Interactive
CSS Code View
The overflow property controls how content is clipped, and it creates horizontal or vertical scroll bars to accommodate the extra content.
Floated boxes
Floated boxes are part of the normal flow. When boxes are floated, they behave as inline elements. That means that they go from being in the document flow to being in the inline content flow of a parent box.
A box is either floated to the right or floated to the left, and it shifts the box to the right or left edge of the parent containing box at the line that the box is on. The remaining content then continues to flow around that box until it runs past the floated element or is cleared.
Floated boxes are central to multi-column page layouts, though that was not immediately apparent as they were first used to flow text around pictures. Nesting floats in one another is the basis for multi-column layouts. Nest one box inside of a floated box, and you have two columns, nest that box again inside another floated box, and you have three, and so on.
Floating Boxes Interactive
CSS Code View
Live Demo
Box A:
Box B:
Box C:
Box D:
Two of the floating properties have been disabled. Enable them and see how the boxes jump into position. Once you do, you will notice that Box D also has the clear right property, which pushes it below Box C. Delete the clear property and see what happens.
Floating Three Column Layout Interactive
A bulletproof three column layout.
CSS Code View
Live Demo
HEADER
CONTENT The outlines show that the floated columns do not go all the way to the bottom. Color any one of them and they will stand out. The solution was to create a background picture to make it look like the columns go all the way down. This only becomes a problem when the columns have different backgrounds. The solution is to use an image that repeats vertically all the way to the bottom.
HTML
<div>
<header>
HEADER
</header>
<aside>
SIDE A
</aside>
<article>
CONTENT
</article>
<aside>
SIDE B
</aside>
<footer>
FOOTER
</footer>
</div>
</div>
CSS3 Multi-Column Property
It is easy to create multi-column layouts using CSS3 multiple columns property. The document flow can create more columns inside a box than is visually pleasing, so change it to one, two, three or four columns, depending on the size of the screen. A good use of this would be in media queries, where small screens get one column, tablets get two and computer monitors get three or more columns.
Multi-Columns Interactive
CSS Code View
Live Demo
What is “Fun?”
“I’ll know it when I see it.”
As designers, we get a lot of similarly elusive adjectives from clients, as they tell us what they want their sites to be: “The site needs to be ‘cool,’” “It should be ‘exciting,’” “I want it to ‘pop.’” When we ask them to clarify, the answer we get back sounds a lot like “I can’t tell you what it is but I’ll know it when I see it.”
“Fun” is a particularly difficult concept to define. And we’re starting to hear it a lot more from clients as we design for different contexts of use.
So what’s a designer to do?
CSS3 FlexBox Property
The Flexible Box Layout Module is designed solve a layout problem where the extra space is automatically divided between flexed siblings. It can align its contents horizontally or vertically, can have the order of the columns swapped dynamically, and can automatically “flex” the size of each columns to fit the available space. Flexbox demo. CSS-Tricks guide to Flexbox.
CSS3 Grid
The CSS Grid defines a two-dimensional grid-based layout system optimized for user interface design. In the grid layout model, the children of a grid container are positioned into arbitrary slots in a predefined flexible or fixed-size layout grid. Grid demo. CSS-Tricks guide to grid.
Page Layouts in CSS are not as straight forward as one might expect, but then, tables were not exactly straight forward either.
As layouts became more complex, a mix between tables and CSS was used, and by about 2007, the bugs had been removed enough that the New York Times, a standard-bearer, could go to a table-less layout based on floats. That broke the ice and after that almost everyone migrated to an all CSS layout
A float is easy enough, and it was introduced by Netscape Navigator 1.1. There is also a clear, to clear the float. It was originally intended to float pictures. The code that floats this example is <img style="float: right; padding: 0 0 10px 10px;" src="http://b.parsons.edu/~dejongo/12-fall/stuff/images/mondrian2.jpg" alt="clear float picture demo">
The next paragraph has clear applied to it. That forces the next element to clear the float. The second paragraph above, for example, does not clear, and continues to flow to the side of the picture.
There are a number of methods to achieve the same goal, but most of these build on the ability to float elements to the right or the left of the containing box. The problem using this method is getting the parent containing element to expand to hold the floated children, as the children can become unruly, and stick out below the parent box (see below for an example).
To prevent that, all kinds of fixes were created, like floating the parent container or the .clearfix method to push the parent box below its floated children. There is a faux column solution that uses a background element to give the impression that all the columns are the same size, and a method called the one true layout that uses margins to push the content into columns, which is similar to one called the holy grail, but they have mostly been supplanted by the overflow: auto method detailed below. For more information and links to tutorials, you can go to CSS tricks or smashing magazine.
When you apply float to an element, you make a box, take it out of the normal document flow, and shift it to the right or left of the containing box. The remaining content flows around the floated element. The floating elements always needs an explicit width. The #bbb and #999 boxes demonstrate what happens when you float boxes to the right, and they are handled as if they were inline elements so that the boxes float next to one another till there is no more space. To stop an element from flowing around the floated element, you have to clear it, as in clear: right;. That way the boxes can float under one another, as demonstrated by the #ddd box. The problem with building a complicated layout with floats lies in browser incompatibility, for it is possible that the page does not degrade properly. To not invite any more problems than necessary, make sure you reset the CSS.
So floats can be used to create columns, but there is another issue to consider.
A containing box will not expand unless there is content. For some reason, when you float a child element, the containing element fails to keep track of it. This becomes unsightly when there is a border or background color on the containing box, and the floating box extends below the border like this.
As you can see, this is not acceptable. The W3 recommends that you put in additional markup and clear: both;, but that is a bit of a hack and requires additional markup introducing an unwanted element at bottom. All kinds of clever solutions were found to create a CSS only solution to that problem, which I need not go into as someone discovered that adding overflow: auto; to the containing box did the trick.
It appears that all is well in CSS multiple column land. If you want more columns, you can make the floated child a parent to another floating child, so nesting floated children inside of floated children.
3 Column Float Demonstration
CSS Code View
HEADER
You will see that the columns fit the content, and that they do not all go to the bottom. This is a problem if you want to have columns with different backgrounds. The solution is to use an image that repeats vertically all the way to the bottom, which I have all ready for you to uncomment. You then have to comment-out the background colors of the columns themselves before you can see it.
HTML markup for the example
<div id="cd-wrap">
<div id="cd-header">
HEADER
</div>
<div id="cd-container">
<div id="cd-side-a">
SIDE A
</div>
<div id="cd-content">
CONTENT
</div>
<div id="cd-side-b">
SIDE B
</div>
</div>
<div id="cd-footer">
FOOTER
</div>
</div>
</div>