Introduction To HTML & CSS
Introduction To HTML & CSS
To
HTML & CSS:
Learn To Code Websites Like A Pro
By Danny Ajini
Of Climb New Heights LLC.
ClimbNewHeights.com
Table Of Contents
Chapter 1: Start Here
Chapter 2: Understanding HTML
Chapter 3: Understanding CSS
Chapter 4: Where To Write Your Code
Chapter 5: Browsers
Chapter 6: HTML Structure
Chapter 7: CSS Structure
Chapter 8: Common HTML Elements & Their Rules
Chapter 9: Common CSS Styles And Their Rules
Chapter 10: Getting Started
Chapter 11: Preparing Images For The Internet
Chapter 12: Manipulating Placement Of HTML Objects
Chapter 13: Margins And Padding
Chapter 14: Other Types Of Positioning Techniques
Chapter 15: Fonts, Fonts, Fonts!
Chapter 16: Semantic Code
Chapter 17: Using Color
Chapter 18: CSS Sprites
Chapter 19: Element States
Chapter 20: Handy Things To Consider
Chapter 21: Flash, Javascript & CSS Animations
Chapter 22: Validation & Troubleshooting
Chapter 23: Minified HTML/CSS
Chapter 24: Grid Systems
Chapter 25: Responsive Web Design
Chapter 26: The Favicon
Conclusion & Next Steps
CSS stands for Cascading Style Sheet and when people refer to CSS they will often talk
about the stylesheet which is the document containing the CSS code. As you can see
above in Figure 2.1, on the left you have a website which consists of HTML & CSS. And
on the right you have the EXACT SAME WEBSITE, however I deleted the stylesheet.
The HTML includes all of the elements that are on the page IE: the pictures, the words,
the links, etc. and the CSS is the code that the website designer uses to denote the color,
orientation, font, etc.
As you can see the website on the right (minus the CSS) looks very much like something
But as you can see, as soon as I began to type the hash mark, a helping hand popped up to
help me choose a color.
This is just one example of how the text editor that you choose can help you get the job
done.
Essentially, the best text editors can help you to remember tidbits of code, help you to
keep your code organized and assist you when you forget essential pieces of code.
Chapter 5: Browsers
I know youre eager to start learning about website building however, the topic of
browsers is one of the most important pieces to the puzzle.
An internet browser is simply the portal that you choose to help you view the abomination
which has come to be known as the internet.
Figure 5.2 Once I click inspect element this window pops up and gives me some helpful information.
Once I click Inspect Element then this extremely helpful Developer Tools window
pops up.
The red x with the number in the corner, lets me know when files which the document
says are supposed to accompany this file are missing.
I can see that the images which arent showing up are a result of a broken path.
A few things that I want to quickly mention:
1. Almost every modern browser has some sort of Developer Tools option however, I
happen to think Google Chromes version is the most helpful and easiest to use.
Google Chromes Developer Tools window is also very cool because it allows you to
edit HTML & CSS directly in the Developer Tools window so you can experiment
with your code before you actually put it to use on your website.
2. As you can see, when I inspected the element the panel on the right tells me every
CSS style associated with the element in question. If there was a style which I
happened to write incorrectly the Developer Tools window would let me know by
putting a slash through the CSS rule. This lets me know that the CSS statement is
not currently being used because it is written incorrectly.
3. These developer tools options are extremely helpful and have many more capabilities
than I even know about or have the time to mention. If you end up becoming serious
about coding, than you should make a conscious effort to learn more about what
functionality the developer tools can offer you.
One thing that is pretty cool about Firefox is this 3D view option. Im not exactly sure
how useful it is. However, it can help you to understand the hierarchy of the page as well
as show you where there may be errors in terms of elements placed incorrectly inside
other elements.
In all honesty, when I tried to initialize the 3D view on my own computer a window
popped up letting me know that 3D view has failed and to check the troubleshooting page
on Firefoxs website. I suspect its because of my graphic card. However, here is a
picture of what the Firefox 3D view looks like.
Figure 5.3 The 3D view option in Firefox is super cool!
Broad Example
If you wanted to target every instance of a particular HTML element you would begin
your CSS declaration with the name of that element.
Examples:
body (Targets the body of the HTML document and all elements contained within)
h1 (Targets all h1 header elements in the document)
a (Targets all links)
Targeting An Element By ID
Classes are cool because you can have as many elements on a page as you want with the
same class.
However, there comes a time when maybe there is only one element on the page which
you want to give a bit of significance to.
An ID is a way to target an HTML element. However, there can only be 1 element with
the same ID per page.
Sure you can have multiple elements with the same ID on the same HTML page.
However, when you go to validate the document it will show as invalid in an HTML
validation program, as this is not a valid HTML technique.
To give an HTML element an ID it is very similar to the class declaration.
CSS Hierarchy
CSS is called Cascading Style Sheets because the rules set for CSS cascade down the
document into other elements. For example, CSS styles that are lower in the document
will over power styles that are higher in the document. A style on line 1 will be
overpowered by a style on line 365 that targets the same element for instance. That means
if you were to declare the default font-family for the document to be be Arial, then later on
in the document you specify Tacoma, than the latter style would take effect.
CSS styles that are more specific in their CSS targeting will over power styles that are
more vague in their targeting. For example a CSS style directed at all paragraph tags will
be overpowered by a CSS style directed at all paragraph tags with a class or id of your
choice.
If you are targeting one HTML object and you give the object two conflicting styles the
browser will render the style that is lower in the document. For example if you give all
headings a margin of 10 pixels and then later say that all headings should have a margin of
15 pixels, the browser will render the latter style.
If the HTML object itself has an inline style than in most cases the inline-style will be
rendered. An example of an inline style would be as follows:
<img src=/images/example.jpg alt=This is alternative text style=float:left; />
In most cases all of these conflicting styles can be bypassed with a declaration of
!important before the closing semi-colon of the CSS declaration.
Heading
Headings are just as they sound. They are text headings which range in size from H1-H6.
H1 being the largest and most important in the eyes of search engines to H6 being the
smallest and least important.
To use a heading simply wrap the heading text with beginning and ending header tags.
Headings are block level elements. This may be obvious but dont mismatch the tags for
the heading.
<h1>This is an H1 heading.</h1>
<h2>This is an H2 heading.</h2>
<h6>This is an H6 heading.</h6>
Images
Images are also pretty self explanatory. Images are inline block level elements. To keep
your code valid, make sure every image you use in your document has an alt specified.
The alt attribute is important for when your image fails to load for any number of
reasons. The alt attribute is also useful for visually impaired website visitors. In both
cases the images would show the alternative text which describes the image so they can
get a better feel for what the website is about.
To use an image simply use the following format.
<img src=path alt=Alternative text />
Obviously the path should point to the place where the image is located and the alternative
text should be replaced with actual alternative text. Since images cant wrap around other
elements the image tag ends itself, as you can see with the forward slash before the ending
greater than symbol (>).
Quick note: your code will still be valid if you leave the alt attribute blank. However, this
isnt the best practice. Essentially it is the alt attribute itself that makes the image valid
and not the text inside.
Links
Links make the internet go around. Links are inline-elements. To use a link use the
following format.
<a href=path>Text, image, or whatever you wish to link goes here.</a>
Obviously keep in mind that the word path should be replaced with the url which you wish
to link to.
Tables
In the past people would lay out entire websites using tables. Today however, that
technique is frowned upon. Tables are great for keeping information neat and tidy. Tables
are block level elements.
To use a table use the following format.
<table>
<th>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</th>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
TH stands for table header, TR stands for table row and TD stands for table data.
Essentially listing the top row as a table header isnt necessary as all rows can just be
labeled as table rows. However, if you wish to style the top row using CSS you may want
to utilize the TH tag as it will make it easier to target the top row.
Forms
Forms are a little beyond the scope of this book. Not because forms are difficult to use but
because they normally require a bit of Javascript or other type of code to work. I wont go
on to mention much about this. However, I will just give you a quick tip and say that in
order for a text area to be valid code you must specify a cols and rows attribute. This
essentially gives the text area a width and height however you can later manipulate these
dimensions with CSS if you wish.
Color
The color attribute always denotes the color of the text. To use the color attribute simply
use the following format. Black is default when it comes to color, unless youre talking
about a link.
color: #000000;
Later on in the book Ill explain how HTML color works and how to use the hexadecimal
system for specifying colors. You can specify color using the hexadecimal system, rgb or
even list them by name.
Fonts
There are a ton of CSS declarations which deal with fonts. Were going to briefly touch
upon a few.
font-family: 1st choice, 2nd choice, last resort;
Fonts are specified by family. More on this later.
font-size: 12px;
Font size can be specified by pixel size, ems, you can even specify by using adjectives
(large, small, etc.)
font-weight: bold;
Font weight can be specified by hundreds (100,200,300, up to 900). 100 being the
thinnest and 900 being the thickest. You can also specify font weight by using bold,
bolder, lighter & normal.
text-transform: uppercase;
Using text-transform you can specify that you want a particular block of text to be
uppercase or lowercase. The text will then be rendered in that specific case regardless of
how its written in the actual HTML document.
line-height: 14px;
Using line-height you can specify the height between lines of text. You can specify the
amount using pixels, ems, etc.
Borders
There may come a time when you want to give something a border. You can specify all 4
borders at once or you can specify one border at a time. (There may be alternative ways to
specify the border however, well just use the basics for now.)
border: 1px solid #ffffff;
To specify a border, begin with the border width in pixels, followed by the style (options
include: solid, dotted, dashed, thin, inset, etc.), followed by the color. To specify a border
on a specific side use:
border-right: 1px solid #ffffff;
border-left: 1px solid #ffffff;
border-top: 1px solid #ffffff;
border-bottom: 1px solid #ffffff;
Floats
Some HTML elements naturally stack on top of each other because they use up all the
width allotted to them and some do not. In order to alleviate this for times when you have
two objects that stack and wish to have them side by side, you can use floats.
To float an object use the following format:
float: left;
You can either float an object left, right or none.
A float basically tells a stack-able HTML element that it should only take up as much
horizontal space as it actually needs rather than hogging up all the horizontal space. Then
it tells the element to begin stacking either left, right or center.
Display
You can use the display attribute to display a block level element as inline, and inline
element as block or not at all.
To use this feature use the following format:
display: block;
Your options here include block, inline, inline-block, as well as none. Display:none; is
for when you dont want to display an object at all.
Overflow
There might come a time when you have a div which you have specified a width or height
for, and you have placed an object inside of the div which extends past the boundaries of
its containing element.
In this case you have an overflow. To style this use the following format:
overflow: scroll;
Your options here include: scroll (which places scroll bars inside the element), hidden
(which hides the excess) as well as visible (this shows the excess).
Position
Later on Ill give you my technique for laying out a website. However, there are a few
different positioning declarations.
To use the position declaration use the following format:
position: relative;
Position has a few options, such as relative (relative to its current position), fixed (fixed in
one position relative to the browser window and doesnt move) and absolute (this is an
absolute position based on any containing elements.)
When you use the position property you must then specify the position based on the
distance from either the top, left, right or bottom.
You do so using the following format:
top: 10px;
You can use any combination of top, left, right or bottom and use any valid unit of
measure you wish. IE: pixels, points, ems, etc.
Things To Remember
There are honestly too many CSS declarations to mention here. Youll have to learn more
as you go along. Some other great CSS declarations include border-radius which gives
you rounded corners as well as some of the CSS3 transitions and animations which are a
little more advanced.
Some things to remember are:
You cant have more than one background image on a particular object
HTML objects inherit default styles
Child elements inherit styles from parent elements
Styles that are lower in the stylesheet override styles which are higher up in the
stylesheet (unless !important is used directly before the ending semi-colon)
You only have to specify as much CSS as you need to. For example if an object
inherited a style that you like, you dont have to redefine the style. Only use as much
CSS as needed.
The Mockup
I begin each website that I build with a mockup. A mockup is essentially a Photoshop
document of what the home page of your website is going to look like.
Figure 10.1 Below is a mockup I created for a friends website.
As you can
see in Figure 10.1 this is an example of a mockup. Its a website design that I was
messing around with for a friend who happens to loves a good bargain.
Its the website that I will be using as an example throughout this e-book because its just a
simple 2 column website.
The mockup is extremely important because it serves as the blue print to your website.
Once you have a mockup, you are ready to begin coding!
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Here Is Where You Put The Title Of Your Website</title>
<![if lt IE 9]>
<script src=http://html5shiv.googlecode.com/svn/trunk/html5.js></script>
<![endif]>
</head>
<body>
</body>
</html>
Open up your index.html and type the above code into your document. This is a
barebones HTML document and pretty much everything that you see above is required to
have a valid HTML document. (In the past a valid HTML document would have included
a lot more declarations.)
DOCTYPE = The document type
HTML LANG = en (English) Note that the HTML tag begins at the top of the
document and ends at the bottom to wrap up the document.
Head = The place where your page title, links to CSS style sheets, Javascript code,
and other miscellaneous code that is important for your website but isnt necessary
for the aesthetics of your website.
<![if lt IE 9]> = The code that follows this is to allow for HTML5 elements to
work in older Internet Explorer browsers. Im not sure that this line of code is
necessary to have a valid document, however it doesnt hurt to add it. if lt IE 9
means if later than Internet Explorer 9. The entire block of code basically means, if
the browser viewing this document is Internet Explorer and if it is, if its older than
Internet Explorer than use this document linked here.
Body = In between the opening and closing body tag is where your HTML goes.
<meta charset=utf-8>
<title>Here Is Where You Put The Title Of Your Website</title>
<link href=css/style.css rel=stylesheet type=text/css />
<![if lt IE 9]>
<script src=http://html5shiv.googlecode.com/svn/trunk/html5.js></script>
<![endif]>
</head>
<body>
</body>
</html>
This line of code links the stylesheet to your HTML document. The href is the path to get
to the document you are trying to link.
Backgrounds
I wasnt sure initially how to structure this e-book. However, Ive realized that the best
way to go about teaching my knowledge of HTML/CSS was to go through some of the
most useful properties and drop tiny morsels of wisdom along the way.
I know I mentioned that you should start each website off with a mockup. However, in this
case since youre just learning its not necessary.
If youve been following so far you should have a blank HTML document with a black (or
possibly other color) background.
Go to your CSS document and make it blank again.
When it comes to doing anything HTML/CSS related, there are many ways to do every
task.
That being said, were going to cover a few different ways to accomplish the same goal,
giving our blank website a super cool background!
Tiled Backgrounds
One of the most popular background options is your standard tiled background.
Of
course you should change images to the title of your images folder if you chose to name
your folder differently, as well as change the name of your actual image file to match the
file you have chosen.
Above is the result of my tiled background.
As I mentioned before with HTML elements all having default styles applied to them,
CSS styles have default properties associated with them as well.
For instance having a declaration for a background-image always denotes that the
background image will be tiled unless you declare otherwise.
Youll see in a minute what other background option choices you have at your disposal.
A quick note about declaring paths.
Essentially, because our CSS file and our images are in different folders then we have to
denote that in the path declaration.
body
{
background-image:url(../images/paisley.png);
}
The ../ in front of the path is there in order to tell the stylesheet that the path to the
image is not in the same folder but is one folder up relative to the CSS folder.
When working locally on your computer you will be dealing with whats known as
relative path declarations. This means that your paths will be based on where they are in
relation to the current folder.
When you begin to upload your files to the internet you will be doing most of the same.
However, there may come a time when you will need to use an absolute path declaration.
One example would be the one you witnessed above in the head of the HTML document.
<script src=http://html5shiv.googlecode.com/svn/trunk/html5.js></script>
Because the Javascript file above is not relative to your website and is located on its own
url, you will need to declare the path beginning with the url.
Simply put, the path will need to be denoted beginning with
http://www.example.com/the-folder-in-question
Gradient Fun!
Ok, as I mentioned above, background images are tiled unless you specify otherwise.
Figure 10.3 Below are two gradient examples. On the left is a gradient tiled on the y-axis and on the right is a gradient
tiled on the x-axis.
You
can make a linear gradient in one of two ways. I used only a simple black to white
gradient to illustrate my point. However, you can get as crazy as you wish with your
gradient. You can even do circular gradients. (Ill show you how after this later)
In order to accomplish to top to bottom gradient youll need an image to tile on its x-axis
(left and right). Since it repeats itself left and right the image only needs to be 1 pixel
wide (you should always be concerned with using as little images as possible to save load
time!)
Choose your two favorite colors to create a gradient. Create a file in Photoshop that is
around 400 pixels tall and 1 pixel wide and fill the file with your gradient.
Figure 10.4 Here I am creating a 1 pixel wide image which will serve as my gradient.
I decided to use
black and blue for mine.
Save your image in your images folder and be sure to remember the name and the
extension.
Go to your stylesheet and type:
body
{
background-image:url(../images/gradient.png);
background-repeat:repeat-x;
}
Obviously replace gradient.png with your filename and extension.
This is the result
Figure 10.5 Below is the result of my tiled gradient.
We declared a background image and told it to tile on the x-axis. It did, however the
default for the background is still white and therefore there is white showing below where
the image was tiled.
In order to fix this well have to also specify a background color along with the
background image so the gradient will look fluid. Lets use our Photoshop eye-dropper
tool in order to get the color code we need!
Figure 10.6 Below Im using the eye dropper tool to get to figure out the color at the very bottom of my gradient. This
will help me to declare a background color and blend my gradient in with the page.
As you can see above we used the color picker tool to find the code for the color that we
need. Now we can fix our gradient and make it continuous!
Go to your CSS and add:
body
{
background-image:url(../images/gradient.png);
background-repeat:repeat-x;
background-color:#00aeef;
}
Obviously replace the hexcode number with the color which you need.
Figure 10.7 Below is my new beautiful continuous gradient!
And
our gradient is now fixed!
Using the above logic we can create a left to right gradient by following the same steps.
Except in this case we use an image that is 1 pixel tall and X pixels wide. And instead
of saying background-repeat: repeat-x; we change it to background-repeat: repeat-y.
Not only do we have control over how the background repeats but we also have control
over the position. The default position for a background is always in the upper left corner.
This allows for a variety of different options.
Figure 10.8 Getting funky with the gradients. This gradient runs along the right side of the browser window!
For
example, the above gradient would be created with a 1 pixel tall by X pixels wide image
which is repeating on the y-axis and the background-position is right.
The code would look like this.
body
{
background-image:url(../images/gradientexample.png);
background-repeat:repeat-y;
background-color:#00aeef;
background-position:right;
}
If youre worried about memorizing each CSS declaration, dont. Each of these things can
be Googled at a later date if you forget. The most important thing is that you understand
the underlying principals and see what is possible using HTML/CSS.
This
website is awesome because:
It allows you to edit the gradient just like you would using image editing software
You can change the orientation of the gradient from vertical, horizontal, diagonal as
well as radial
The CSS is generated for you and they included CSS declarations for the most
common browsers as well as a backwards compatible solution for older IE browsers
They have pre-made gradients
Best of all it saves you a ton of time
Once youve created a gradient youre happy with, simply copy the CSS and paste it into
your style sheet.
Above is the result. Obviously we probably dont want to use Times New Roman
however, well learn about fonts a little later in the book.
72 DPI
If youre a graphic designer or come from a print background than you may be familiar
with image resolution.
Typically, when working with images that are being prepared for print the standard
resolution is 300dpi. However, when it comes to the internet most images are 72 dpi. In
some rare instances you may encounter pictures with resolutions which are upwards of
around 90 something dpi, 72 being the standard.
You also want to make sure that the images are saved using the correct file extension and
that you are optimized for the file extension youve chosen.
As you can see from the image above, that tiny spot on that dogs forehead alone has so
much variance in the color from pixel to pixel that saving this image as a .png or .gif will
cause your website to load extremely slow.
Saving your photographic images as a .jpg is great because in photo editing programs such
as Photoshop, it gives you the option to lower the quality of the image so that the file will
be smaller.
You are able to lower the quality of the image and see how the final image will be
effected, as well as how long the image will take to load BEFORE you actually save the
file.
What I like to do is lower the image quality, while watching the estimated load time of the
image. This allows me to get the image to a point where the image quality is acceptable,
while the image load time is not excessive.
I took this same image above (it is 1920x1080 pixels this is very large for internet
pictures) and using the Save For Web And Devices menu in Photoshop figured out how
long this same image would take to load using the most common file extensions.
Figure 11.2 Below you can see a preview of the load time on the puppy picture using various image extensions.
As you
can see, for the same exact image, saving this image as a .png would cause this image to
take 402 seconds @ 56.6 Kbps, a .gif would take 190 seconds and a .jpg at 100% quality
would take 114 seconds.
Keep in mind the .png and .gif could be altered to load in less time however the image
quality would drastically suffer but, the .jpg could be lowered in quality with minimal
difference in the final product and still load extremely fast.
The picture above would be better suited to be saved as either a .gif or a .png. If the image
were to be animated it would most certainly be saved as a .gif because .gifs support
animation.
Both .gif and .png support transparent objects, however .png is much better at
transparency.
You probably cant tell by looking at the above picture however it has a transparent
background. When you try to save an object with a transparent background as a .jpg the
transparent part will be turned white.
Lets do the same experiment as we did with the dog pictures.
As you
can see, when trying to save the above image as a .jpg at 100% image quality the image
will take more than twice the amount of time it would have taken the .gif and .png to
load. Not to mention the fact that the .gif and the .png will have transparency.
Also not to mention the fact that if if you did try to save the above image as a .jpg and you
tried to lower the quality in order to save load time, this would happen.
Figure 11.4 When attempting to save this image as a .jpg some mild compression artifacts beings to appear.
As you
can see, I lowered the quality of the image down to 31%. At 31% quality the image takes
4 seconds to load. And as you can see, lowering the quality of the image has caused the
image to suffer greatly.
If youll look at the areas on the image that I have circled you can see subtle variances in
the color of the individual pixels causing an extremely ugly effect to take place.
This is known as a .jpg artifact.
of a colored background.
When I looked closer I noticed that there were tiny pixels around the edge of the
transparent image which werent quite right.
In order to illustrate the problem, Ill create a web page with a red background, save the
image above as a .png as well as a .gif and place the image on the page to show you the
issue I was having.
Figure 11.5 The small amount of white pixels surrounding the picture below is an issue of matting.
This is
what happens when you save the image as a .gif. As you can see there are white pixels
surrounding the image in certain places.
Now, lets try the same thing with a .png.
Figure 11.6 Same image saved as a .png. The .png offers superior transparency without having to mess around with
matting.
As you
can see the image now doesnt have those pesky pixels there anymore!
But what caused this?
In all honesty, this was a problem which effected me for a while when I first started web
design. And even when I asked my teacher at the time he seemed to be of no help.
What Ive found is that this effect is caused because of what is known as anti-aliased
pixels. When it comes to transparent pixel based pictures. The pixels around the outside
of the image cant be a solid color. If that were the case then the outer edge of the image
would look blocky.
It is a little
hard to tell, but I filled the page with a bunch of block level elements and a few inline
elements.
The difference between a block level element and an inline element is that a block level
element will take up as much space as it needs vertically and as much space as it can
horizontally.
As you can see I have inspected the H1 tag (thats whats known as a heading 1) and the
blue and pink region illustrate the amount of space that the object takes up. Clearly, the
Heading 1 element is taking up the entire width of the page.
If I were to put the same H1 tag in a container which spanned only half the width of the
browser window the H1 tag would still take up as much room as it could horizontally.
Except in that case it would be limited by its container which only allows it to take up
half the width of the browser window.
The page above has mostly block level elements and as you can see they stack on top of
each other.
The very last line however, has 3 different inline elements. Lets choose the inspect
element option to learn more about the nature of those inline elements.
Figure 12.2 I clicked inspect element on a span element. The line with the span element contains 3 different span
elements. Notice that they are all on the same line. This is because they are inline elements.
The
very last line of the document includes 3 span tags. A span is a type based element
which holds less significance/ importance than a paragraph which could be considered the
spans older brother.
As you can see as I inspected the span element, the element itself takes up only as much
space as it needs to. This is the same with all inline elements.
The relationship between block level and inline level elements is important to know
because there may come a time where you want to have two block level elements directly
next to each other.
Or there may come a time where you want to display an inline element as though it were a
block level element.
Inline-block Elements
Inline-block elements are inline elements that have a width and a height, rather than only
taking up as much space as necessary. This is something that is encountered rarely but is
still great to know and another tool in your arsenal.
Floating Elements
Before we get too deep into this Ill show you basically how people normally set up
websites.
I will do so by taking a mockup which Ive already done and using a yellow outlins to
show the different dividing boxes which I used to create the layout.
In modern website development people use what is known as a div to separate and
layout their content.
A div is a block level HTML element and is very handy for laying out websites if you
know how to manipulate them.
Figure 12.3 I wrapped every div this page contains in a yellow box to illustrate laying out a website.
If
youre a little confused than thats great! It means you understand how a block level
element works.
If youre not confused than basically each of these boxes, based on the way theyre
supposed to behave should be stacked on top of each other. In fact they would be, if it
werent for CSS.
Lets revisit the picture we saw earlier in the book.
Clearing Elements
Floats and clears go hand in hand. Lets say that you have two floating objects inside of a
container object.
Using CSS you have specified a red background for the container element and the two
floating objects dont have any kind of background.
The container object is wrapped around both objects so what will the background of the
entire area be? If youre a logical person than you would assume that since the container
has a red background that the background of the entire area would be red.
However, since floating objects dont behave quite like block level elements anymore they
dont trigger the container element to wrap completely around both floating elements.
I know it sounds a little confusing so Ill just illustrate it.
Figure 12.3 Below are two divs side by side inside of a container div. I specified for the container div to have a red
background however there is no background color presentwhat gives???
Ok, so
above youll see the result of what I was talking about.
I created a div with a class of container. I said for the div to be 1,000 pixels wide and be
centered in the middle of the page.
Within that container div I created two divs which are supposed to have a width of 50%
and are to be floated left.
They are stacked side by side however the container isnt wrapped around them. We
know this because the container div is supposed to have a red background.
Lets use the inspect element option to see what happened to our container div.
Figure 12.4 I clicked inspect element on the container div only to see that it isnt wrapped around the elements
inside it.
As you
can see the container is not wrapping around the two divs which are inside of it.
The reason for this is because the HTML document doesnt really see floating objects as if
they were there.
Its a little hard to explain so lets put a block level element after our two floating divs and
see what happens.
Figure 12.4 Its beginning to look a little better, we can see the red background but it isnt completely covering the
elements inside it.
I
placed a H1 tag after both divs and as you can see the container now sees that there is a
block level element inside it and wraps around it.
You may be wondering why the H1 tag didnt go below both of the floating divs.
This is because, just like we write from left to right. HTML goes from left to right. And if
you dont specify otherwise each element will try to go directly into the upper left corner
of the screen.
In order for the H1 tag we just placed in the document to go beneath the two floating
objects, we have to use another CSS property called a clear.
I purposely put half as many objects into the right column div as the left column div so it
would be shorter. And because there is nothing there to tell the H1 tag to clear both of
those floating elements, it goes to the nearest upper left corner that is available.
The clear property has a few different options. You can either clear objects to the left, to
the right, or both.
Now, let me give that H1 tag a class of clear. And then I can use CSS to specify that any
element with a class of clear should clear both.
Above
is the HTML as well as the CSS thats involved. And below is the result.
As you
can see, floats and clears are extremely helpful when it comes to laying out websites.
Next we will learn about margins and padding which will also be helpful when it comes to
lay outs as well as styling objects the way you want them to look.
Margins
A margin works to basically serve as a barrier, pushing objects away from other objects.
If you set a margin of 10 pixels to an object that means that no other HTML element can
get within 10 pixels of that element.
While margins dont add to the actual size of the element, they do sort of add size to the
coverage of the element.
For example, if you were to have a containing div which you specified to be 1,000 pixels
wide. Then you placed two floating divs inside the container. Each of the two floating
divs were said to have a width of 500 pixels. Then both divs would fit directly side by
side with each other in the container.
However, if you were to give both of the floating divs a margin of 10 pixels, they would
stack on top of each other because they wouldnt have enough room to fit side by side.
Figure 13.1 These two divs are supposed to sit side by side inside of a 1,000 pixel wide container. Each div is 500
pixels wide. However, now because each div has a margin of 10 pixels around, they dont fit next to each other anymore.
Above
is the same website from earlier. However instead of the containing div having a red
background I gave each of the floating divs a red background, as well as a margin of 10
pixels around the entire border.
As you can see, even though the width I specified was 50% they dont fit side by side
anymore because of the margins. And as you can see by the inspect element tool in
Google Chrome, it illustrates the margin using that peach type color.
Padding
Padding is almost identical to margins, except padding works inside the element. If you
were to specify a 10 pixel padding to an element, the element would grow 10 pixels on
each side. Also, no element would be able to get within 10 pixels of the edge of the
element.
In the above example you can see that the text inside each div actually touches the edge of
the div itself. This isnt very attractive, so lets give those divs a padding of 10 pixels so
we can see what happens when we do!
Figure 13.2 I gave this div a padding of 10 pixels all around and clicked inspect element.
As you
can see the text is not touching the edge anymore. Google Chrome uses a green color to
denote padding however you arent able to tell in this example because its being
overpowered out by the red background of the divs.
Negative Margins
There may come a time when you want to position an object and you find no better
alternative. This is when you can use negative margins.
Before I even mention how or why you would want to use them Ill say that this isnt the
most professional option. However, I have been known to use this HTML cheat code
from time to time.
In all honesty, you probably wont find an excuse to pull this trick out of your hat until
you become a little bit more advanced as a website designer.
And I cant think of an example that would be understandable to the person who is just
getting acquainted with HTML/ CSS.
Ive used a negative margin in the past when dealing with code that Im using in my
website that I havent written. And for some reason I cant get a particular object to be
where I want it to be using conventional means. Thats when Ill begin to start messing
with a negative margin in order to push an object to go where I want it to go.
As you can see, Ive created a class called container and specified a margin of 0 auto.
What this means is that on the top and bottom of this container there should be a margin
of 0 pixels and on the left and right the margin should auto regulate.
This is a great technique however, dont go thinking that you can center ANY object using
this technique.
In order for this technique to work:
The object needs to be a block level element (or at least specified to display block
using CSS)
The object needs to have a width specified
The object cant be floated
The object cant have a fixed or absolute position (well cover that next)
Relative Positioning
This type of positioning is relative to the objects original position.
Basically after youve laid out some objects on the page. You may find that a particular
object is not exactly where it needs to be.
Using relative positioning, you simply specify that the position of that element is
position: relative; and then you are able to move it based on its original position. You
can say top: 10px or whatever the case may be using top, bottom, right & left.
Absolute Positioning
Absolute positioning is absolute, however it is based on any parent elements. For instance
if you want to position an object absolutely and that object was inside of a div. The
position you specify will be relative to that div.
If the object is not wrapped in other elements it will be relative to the HTML page itself.
Absolutely positioned elements dont have any effect on other elements. They wont push
any other elements out of the way and are basically taken out of the general flow of the
document.
Fixed Positioning
Fixed positioning is relative to the browser window itself. In other words when you open
your web browser, depending on your screen size, if the browser is minimized or full
screen, etc.
As you scroll a fixed position element wont move. Ive used this in the past for times
when I wanted the background of the page to be a fixed image and I didnt want the image
to scroll as the page scrolled.
Ive also used this for a social media sharing box which was affixed to the side of the
browser window.
Other uses you might have seen before include the arrow at the bottom right of the screen
that pops up when youve scrolled a significant amount. (The button that allows you to
quickly scroll up to the top of the page.)
Using Positioning
In order to use this type of positioning you simply have to specify the positioning type
using CSS.
One line of CSS will be dedicated to:
position: (relative, fixed or absolute);
Followed by lines of code which will tell WHERE to position the element based on: top,
right, left, and bottom. You are able to use pixels, points, Ems, etc. as your unit of
measure.
As you
can see my text editor is trying to provide me with a list of suggestions.
Google Fonts
Google has a library of web safe fonts listed at www.google.com/fonts where you can find
a font that you like and use it on your web page.
Figure 15.1 Below is the Google web font archive located at www.google.com/fonts.
Above
is a screen shot of Googles font website. On here you can choose the font you want to
use, as well as the weights of the font that you want to use. (The weight is the thickness of
the font.)
I will warn you however, the more Google fonts as well as the more weights that you
choose for your project the longer it will take your website to load.
In order to use Google fonts, simply choose the font you wish to use. Google will give
you the link to a CSS stylesheet that you will have to link to in the header of your
document. Then you will need to use the font-declaration that they give you whenever
you want to use the font.
Figure 15.2 I am able to use as many font weights as I wish. However on the right, the page load graphic will tell me
how much load time the fonts will add to my site.
As you
can see above once youve chosen the font, you can choose the font weights you wish to
use. Then Google updates the Page Load Tool to let you know how much the fonts will
effect page load time.
Once youre done, scroll down to see
Im
pretty sure Ive mentioned this but different browsers render the EXACT same font
DIFFERENTLY. This is important to know because what looks great in one browser may
look totally weird in another if the font is of a slightly different size.
Lets check out how the same font renders in Firefox, Google Chrome and Internet
Explorer. Keep in mind that these fonts are supposedly Google fonts. I think youll be
surprised!
Above
youll see Open Sans, rendered in Google Chrome, Firefox as well as Internet Explorer.
As you can see each font appears slightly different. Each line of text is a different length
even though each line contains the EXACT same characters.
And the funniest thingGoogle Chrome isnt the best at displaying its own font. Internet
Explorer, the worst browser of all time, is arguably the best at displaying fonts.
The CSS
comments are highlighted in the above picture. I think CSS comments are great when you
have a specific section of your website that a large chunk of CSS styles correspond to.
You can place a CSS comment at the beginning and end of the chunk of code to let others
know what the styles were meant for.
Above
youll see an example of a CSS sprite image that I created. I created black and white
versions of the same social media icons as well as red versions which would be used when
the user hovers over the icons.
As youll notice I made use of the Photoshop guides and the ruler is set to pixels. This is
important because these coordinates will be of use to us later.
}
Above is the hover state for the black Facebook icon as well as the white Facebook icon. I
made the graphic so that both white and black social media icons would have a red hover
state, which is why both of these use the same background image and CSS sprite
coordinates.
As you can see above, the red hover state is 0 pixels from the left and 130 pixels from the
top.
This topic may be confusing to some so dont be afraid to do a little bit of your own
research as well as experimentation to learn more. I mostly wanted to tell you about this
technique so youd have it as part of your arsenal.
Above is
a screenshot of the Google Chrome developer tools and this is another reason why I love
Chrome so much for coding websites. After you right click and inspect element on an
object. You can right click in the developer tools window and go to force element state
followed by the state you want to see.
This is great for testing your CSS, because as I mentioned before you can style all of these
element states using CSS.
Active
Active refers to an active link.
Hover
Hover refers to a link or object that is being hovered over with the cursor.
Focus
Focus refers to an input element which is currently active. For example when youre
filling out a form and you hit the tab button. The next form field to get the blinking cursor
in it is the field that has focus.
Visited
Visited refers to a link that you previously visited.
Apparently, they fixed this issue in newer versions of Internet Explorer. However when
you hit F12 you can open the developer tools window. I used the window to show what
the website would look like using Internet Explorer 8.
As you can see there is a blue border around the image. In order to combat this I add the
following style to EVERY stylesheet I write.
a img
{
border:0 none transparent;
}
It targets all img (images) wrapped in an a (link). In case you dont understand the CSS
declaration, the standard protocol for defining a border is border: (width in pixels)
(style:solid, dotted, dashed) (color);. So I specified a border 0 pixels wide, no style and
the color to be transparent.
Global Resets
So as I mentioned earlier, each HTML element has a default style attached to it. Different
browsers have a bit of leeway when deciding how each element should be displayed.
For this reason many people link to a CSS stylesheet known as a reset. This stylesheet
basically styles each element in a way which is uniform across all modern browsers.
I dont feel like this is necessary. However I do use the following style in all my
stylesheets.
html, body
{
margin:0;
padding:0;
}
Some people like to add * along with html and body. The asterisk is whats known as a
wild-cat and basically targets EVERY element. However, I feel that just denoting html
and the body element is good enough.
Default Font
By default, the font will be Times New Roman (or Mac equivalent). To get around this
you can specify the default font of your choice at the top of your stylesheet by targeting
the body with the font-family of your choice.
body
{
font-family: Arial, Helvetica, Sans-serif;
}
Developer Tools
One of the first things that I do when faced with problem is to use developer tools in the
browser that Im viewing the website in.
Pretty much every modern browser is equipped with developer tools to help you figure out
your code.
Google Chrome happens to be my favorite because you are able to edit the HTML and
CSS directly in the developer tools window and preview the changes before you commit
them to your document.
If you notice that a certain CSS style isnt working correctly, check your developer tools
and see if there is something wrong.
Google Chromes developer tools window will put a slash through any CSS style that
either:
Is written incorrectly
Is meant for a different browser (some CSS styles arent global yet so they have
different prefixes for Mozilla and WebKit based browsers) Google Chrome will put
a slash through all Mozilla based styles
Figure 22.1 The Developer Tools window is telling me that the style is not taking effect for some reason, the caution
symbol next to the style lets me know its invalid.
W3C Validator
The second way to diagnose your HTML/CSS is to validate it. W3C stands for World
Wide Web Consortium and all HTML has standards.
When you are having a particularly difficult time with your code it helps to validate the
code and see if it throws any errors. Sometimes your code isnt behaving properly
because it is invalid.
Simply go to http://validator.w3.org (or Google W3C validator) and there are a few
different ways to submit your code.
You can either submit the entire url, you can submit by file upload or you can simply copy
your entire HTML document and paste it into the textbox.
Once W3C validator checks your code theyll let you know if you have a missing tag, if
you have a mismatched tag or if you did anything else that is against protocol.
The Viewport
One difference between static and responsive website design is the fact that with
responsive design you need to designate that the width of the screen should be the width
of the website.
You do this by adding a declaration to the head of the document. Also in this declaration
you can specify if the user can zoom in as well as how much they can zoom.
<meta name=viewport content=width=device-width, initial-scale=1>
Above is an example of one of these declarations.
Specifying Widths
In static website design, when we create a 2 column layout, we think of how wide we want
our columns to be in pixels and create them.
However, when it comes to responsive design, static widths dont cut it.
When you want the widths of objects to change with the width of the browser window its
imperative to designate widths in percentages.
This way your website stays in proportion whether the device is 1,200 pixels wide or 350
pixels wide.
Responsive Images
The width of your images is also important because as the screen gets smaller your images
obviously cant be full resolution or else your end user will have to scroll on their phone to
see the entire picture.
To alleviate this you need to specify a width or maximum width of 100% or less. The
height can be auto regulating by simply specifying that the width be auto. That is, an
automatic height relative to the current width.
Responsive Type
Obviously when your screen is wide all Heading 1 elements can be large, however when
you view the same website on a smaller screen that heading will most likely take up the
entire screen.
Since this isnt the most aesthetic way to build a website, some people like to specify their
font sizes in ems rather than pixels.
I for one dont like to do this so I use the next topic to alleviate this.
Responsive Navigation
Obviously when your screen reaches a point below 1,000 pixels you cant have a wide
navigation bar anymore. At some point the width of the browser will be too narrow to
support your navigation bar.
However, dont fear because there are a variety of responsive navigation solutions to
choose from. All you have to do is Google it!
Something To Remember
Remember that media queries should go at the end of your CSS document because when it
comes to CSS the things at the bottom hold more precedence than the things at the top of
the document.
As the browser window gets smaller the media queries that pertain to that browser width
will begin to take effect and the CSS styles that pertain to wider screens fall back.
If you encounter a particularly difficult CSS style that doesnt take effect and youve tried
everything and done your developer tools research, than you can add !important just
before the semi-colon of the CSS style declaration. !important gives the CSS style
precedence over any other inherited styles.