Getting started with PHP: what it is and how to get it working

Ok, you can build a beautiful, complete site with some moving parts here and there using HTML, CSS and JavaScript/jQuery. Time to kick it up a notch: using PHP, a popular programming language used for building web sites to make your life easier and your site more powerful! In this article you’ll do 2 things:

  • Learn about what PHP is and does for you
  • Get online hosting and the means to use it for building your PHP site

What is PHP?

PHP stands for Pretext HyperProcessor or something, but whatever. More interesting is the definition of the official php.net site:

PHP is a popular general-purpose scripting language that is especially suited to web development.Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.

Ok, sorry, that’s still not useful.

Here’s some of the things PHP can be used for:

  • Including one piece of HTML code ( (for example the <head> part of your site)) into another, so you don’t have to copy-paste big blocks of code across pages.
  • Catching information that a user sends to you with a HTML form
  • Making your site show different things depending on the time of day, the visitor’s IP address…
  • Generally adding cool ‘programming logic’ to your site, with IF statements and loops and variables and things like that.
  • And lots, LOTS more.

But, we can keep it at “it’s yet another language for building web sites” and try to get to the part where you see the use rather than read about it as fast as possible.

PHP requires a server to run

So far, all it took to work on your web site is save a couple of files and open them in your browser directly.

Those days are over.

PHP is a complex language, and requires a server running some magic PHP-interpreting software that turns your notepad musings into actual stuff showing in your browser.

By the way, the word ‘server’ is used, roughly, to indicate the following 2 things:

  • A physical computer, just like the one you’re on now,, specialising in handling online traffic. That means it typically has no screen, a huge-ass hard drive, and resides together with thousands of identical buddies in some data center. Google and Facebook have lots (and lots and lots) of servers for example.
  • A piece of software that can handle incoming ‘connections’ or ‘requests’ from ‘clients’ (a browser is a client for example), and do stuff with them, like execute PHP code and give those incoming requests something back. The piece of server software that’s most relevant to what we are talking about here is called Apache.

Feeling more geeky by the minute, eh?

Get an online web host that runs PHP

Sit down, we need to talk. By now I feel we have established a relationship, albeit a peculiar one stooped in a bizarre mix of condescension and fatherly advice. But it’s also one of trust. Did I ever lie to you? Of course I did, but not on purpose, I promise.

That is why I want to ask you to follow this advice, which is for the first time in the course of this site to pay for something, and trust me that it will be worth it:

Take your wallet, head over to HostGator, and purchase their (cheapest) web hosting plan. Now.

This will give you the power to have a PHP site online, where you’ll want to get it anyway, and get used to some actual ‘putting code online for the world to see’. But the main reason is that you don’t have to worry about setting up all the server stuff that goes into interpreting PHP code.

It takes about 2 minutes, and costs about 50 bucks for a year, and it’s more than worth it. Come back here when you’re done.

Download your FTP client and set it up

Great, you have your online web host account! Just a tad more work and we’re all set to crank out another ‘hello world’. It’s your last one, and it will taste the sweetest of all.

To put files online (on your server), we use ‘FTP’, and to transfer files with FTP we need an ‘FTP client’. (the clever among you recognise how this fits in with some of the terminology about servers we mentioned above)

Download and install FileZilla.

Configure a new site on FileZilla, using the FTP data you can find in your HostGator backend.

Running PHP on your local computer

Ok, you can also do this. If you are on Windows, download and install WAMP, if you are on Mac, download and install MAMP (they will keep bugging you about MAMP Pro, but ignore that – the free MAMP has all you need). These programs allow you to run a PHP site locally, so you can keep building your website just by saving .php files and refreshing your browser.

The workflow of building a site with an online PHP host

It’s all the same as that for a HTML site, except that you now also upload the files to your online web space using FTP with FileZilla.

Conclusion

Takeaways:

  • So far we only made our sites show things. PHP allows you to make it do things.
  • Your browser cannot simply open php code files. Instead, PHP requires a server, typically ‘Apache’ to interpret the code, and execute it.
  • PHP is amazingly powerful, and Facebook and Wikipedia are among the sites built with it, as well as every WordPress site like the one you are reading now.
  • PHP is hard. It’s actual programming instead of specifying how something should look. Prepare to be frustrated. And feel victorious you got something to work. And frustrated again.
Advertisements

Intro to Javascript and JQuery: hello world!

Ok, so by now you have a pretty solid grasp of HTML and CSS, using them to define how a web site looks. However, there is another aspect we didn’t touch on so far: specifying how a web site should behave.

For this we introduce a language to tell our browser what to do and when to do it: JavaScript.

Here are some of the things the language Javascript is capable of:

  • Detecting when a user clicks something, or hovers his mouse over something.
  • Changing how things look with CSS, after the page has already loaded (for example, when the user clicks something!)
  • Moving HTML elements around on the page, showing and hiding them.
  • Show those little message boxes with an ‘ok’ and ‘cancel’ on them. Such a box is called an alert.
  • Make the browser load new content online and show it in the page after it is already fully loaded (this is called ‘AJAX’).

Cool huh? Javascript is amazingly powerful, and used all over the place. Actually, it’s the most used language in the world.

So what is jQuery (which you’ll often encounter in the context of javascript)? jQuery is a Javascript libraryi.e. a set of javascript code that makes it easier for developers to build something in Javascript. And, well, many have! There are zillions of so called ‘jQuery plugins’ out there, that you can just download for free, include in your site to make it do something cool.

Javascript can be specified within the page or in a separate file

… So it’s very analogous to CSS! Javascript within the HTML can be specified within <script> tags. So let’s have a ‘hello world’ in Javascript, by inserting this somewhere in your HTML page:

<script>
//this is a JS comment which will be ignored by the browser
alert('Hello world! This alert is triggered using JavaScript within the HTML code!');
</script>

Or you can write it in a separate .js file and link to that.

First, write the following one line in a text editor, and save it as script.js in the same folder as your html file:

alert('Hello world! This is some code in a separate .js file!');

(no <script> tags in the external file, that’s right!). Now link to that file putting the following line between the <head></head> tags:

<script src="script.js"></script>

Now, if you save all that, and did things well, opening your page in the browser should have it show something like this dialog:

Screen Shot 2014-01-26 at 17.53.46

 

I’m sure you already noticed some things about JavaScript just from that code, for example that Javascript lines end with semicolons (;). Good on you!

Use jQuery to add cool new functionality to your page

In this phase, we will not spend time learning how to write lots of Javascript ourselves. That’s because your energy in learning ‘real programming’ is better spent in learning PHP, which will be introduced shortly.

But you need to understand a bit about Javascript and what it is, enough to take advantage of the thousands of cool jQuery plugins to boost your page, and to not feel completely powerless if something is going wrong with your page that may be related to JS.

Fonts in CSS

A ‘font’ or ‘typeface’ is, well, how the characters on your screen look. There are ‘serif’ and ‘sans-serif’ fonts.

If you don’t tell it otherwise, your browser will show text in the Times New Roman font. But, please, tell it otherwise.

Specifying font family

Use the font-family property in CSS to change the font, for example putting your entire site in the much prettier Arial font by adding this rule:

body {
font-family:Arial;
}

… Yeah that should about do it.

Font size in CSS

Another interesting and often-used one is font-size. Often specified in pixel (px), unless you want to be all fancy and use the ’em’ measure. But you don’t want to be all fancy, so for your first year as a web designer you can just go like this example:

<div class=”quote”>”This is shown bigger than usual”</div>
<style>
.quote {
font-size:20px;
font-family:Helvetica;
}
</style>

Conclusions

For some reason, I hate thinking too much about fonts. I am hoping one of my fellow writers on this site will cover this topic for realsies.

Rounded corners, gradients and box shadows with CSS

Up until about 5 years ago, the internet was stuffed with tutorials on the following three topics:

  • Rounded corners
  • Gradients (one color ‘fading’ into another)
  • Shadows

That was because CSS didn’t really include a straightforward way to do them – but everybody wanted them. Then CSS3 came along, and included straightforward ways to do this. So now everybody’s raving about ‘flat’ design again. Go figure.

That said, rounded corners and gradients are still used a lot, and once you know what they are you’ll start spotting them everywhere. That is because, like the margin and padding we already added to your CSS arsenal, they provide great subtle ways to make your page components more visually pleasing. To just give one example, here’s the product list at the front page of the – rather famous – guys at 37signals:

Screen Shot 2014-01-23 at 11.28.30

For shits and giggles let’s create a non-fugly ‘mini template’ from scratch that uses pretty much every one of the previous lessons, and then spice it up with rounded corners, gradients and drop shadows for a more ‘polished’ look. So flex those finger muscles, close your Facebook, tell your wife to go to bed! Here’s what we’ll build towards:

Screen Shot 2014-01-22 at 23.39.52

Note that this will not look the same in older browsers, especially since we are going to ignore ‘browser-specific’ versions of each of the CSS rules. But keep in mind that there are browser-specific versions of these rules, and just google ‘cross browser gradients’ for example to get copy-pastable versions of the below that work in older browsers.

Starting point

Let’s start with some basic HTML with class names indicating the structure of our site:

<!doctype html>
<html>
 <head>
 <title>My first web page!</title>
 <link rel="stylesheet" type="text/css" href="style_bubbly.css">
 </head>
 <body>
 <!-- actual content comes here -->
 <div class="container">
 <div class="header">Hello World!</div>
 <div class="navigation">
 <a href="http://www.google.com">Some link</a>
 <a href="http://www.google.com">Some link</a>
 <a href="http://www.google.com">Some link</a>
 <a href="http://www.google.com">Some link</a>
 </div>
<div class="contentblock">
 <h3>A header</h3>
 <p>
 This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it!
 </p>
 <p>
 This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it!
 </p>
 </div>
<div class="contentblock">
 <h3>A header</h3>
 This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it!
 </div>
<div class="contentblock rightmost">
 <h3>A header</h3>
 This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it! This is my first web page, thank you for visiting it!
 </div>
<div style="clear:both;"></div>
 </div>
 </body>
</html>

As you see, in the HTML we link to an external style sheet. In the same folder, place the following CSS in a file and name it bubbly_style.css. For starters, and just to see everything works, let’s just define some colors and give everything font Arial:

body {
 font-family:Arial;
}
.container {
 background-color:#eeeeee;
}
.header {
 background-color:#4466aa;
 color:white;
}
.navigation {
 background-color:#777777;
}
.navigation a {
 color:#ffffff;
 text-decoration:none;
 background-color:#555555;
}
.navigation a:hover {
 background-color:#333333;
}
.contentblock {
 background-color:#ffffff;
 border:1px solid #dddddd;
}
.contentblock h3 {
 color:#888888;
}

Remember, no <style> tags for CSS in an external file! If you did everything correctly it should look something like this:

Screen Shot 2014-01-23 at 11.10.40

Positioning the elements

Now we will build the CSS rules for each of the elements that we put in our HTML, targeting their class names.

What follows is a typical exercise in CSS positioning. We will first center the container element using margin-left:auto and margin-right:auto, and add background and some margin and padding, replacing your original .container rule with this:

.container {
 width:1000px;
 padding:20px;
 margin-top:10px;
 margin-left:auto;
 margin-right:auto;
 background-color:#eeeeee;
}

(feel free to add this to your CSS file, save and refresh to see what you get in the browser!)

For the header and nav, we make the font a bit larger, center the text with text-align, and give them some margin and padding:

.header {
 margin-bottom:10px;
 padding:10px;
 height:50px;
 font-size:45px;
 text-align:center;
 background-color:#4466aa;
 color:white;
}
.navigation {
 margin-bottom:20px;
 padding:10px;
 font-family:Arial;
 background-color:#777777; 
 text-align:center;
}
.navigation a {
 color:#ffffff;
 margin-left:5px;
 margin-right:5px;
 text-decoration:none;
 background-color:#555555;
 padding:3px;
}

Things are looking up! We are here:

Screen Shot 2014-01-23 at 11.16.15

The content blocks we float left to line them up next to each other. Then we give them some margin between them, but note that the right one does not need have any margin or it would look ugly. So we set  that margin-right to zero again with a separate class.

Note the math going on: for the 3 blocks to position nicely next to each other and evenly spaced: their widths and the space between them (margin) adds up to the container element width minus its left and right padding. We can literally make that a formula. adding the widths, paddings and margins from left to right:

first block + margin between + second block + margin + third block = container width
(10px + 300px + 10px) + 20px + (10px + 300px + 10px)  + 20px + (10px + 300px + 10px) = 1000px

Try to truly understand and visualise that! It’s a great way to get that box model.

So here’s what we do.

.contentblock {
 float:left;
 margin-right:20px;
 margin-bottom:20px;
 padding:10px;
 width:300px;
 background-color:#ffffff; 
border:1px solid #dddddd;
}
.rightmost {
 margin-right:0;
}

Let’s see if we got all the numbers right:
Screen Shot 2014-01-23 at 11.18.59

Whoops, looks like we didn’t! It’s because we forgot the 1px border, so we should add some pixels to our container to fit them in. Changing the width rule in .container to 1008px instead of 1000px fixes it:

Screen Shot 2014-01-23 at 11.21.31

Starting to look really good! Ok, now we can proceed to the ‘polish’ we added to make it look more modern.

CSS3 rounded corners

Adding rounded corners is really easy, with the border-radius CSS rule. Let’s add rounded corners to ALL blocks, including container and header:

div {
 border-radius:5px;
}

CSS3 Linear gradient

A gradient is one color ‘fading’ into another. A linear gradient is by far the most useful one, and we can add it to the .header rules like this:

background: linear-gradient(#4466aa, #112233);

Note that we kept the ‘flat’ background-color rule in there as well! Browsers that don’t understand the CSS3 will just use that one.

CSS3 drop shadow or ‘box shadow’

Last but not least, let’s add a bit of shadow to each of our content blocks. Note that this is often done with pictures as well. Add this to the .contentbox CSS rules:

box-shadow:5px 5px 5px #999;

You may also remove that 1px border line that was there, and set the .container width back to 1000px. The drop shadow by itself adds enough of a ‘frame’ not to need an explicit border too anymore.

Done!

Aaaaand we’re there! If you did everything well, and I didn’t forget anything in my explanation, we are at the page we wanted to reach:

Screen Shot 2014-01-22 at 23.39.52

Not as hard as you would think, right? Feel free to add real content and pictures to those blocks, make the site consist of multiple pages, so the navigation links make sense (with perhaps a subtitle below the main one to indicate where you are within the site), etc…

If you followed all of this along without too much trouble, and the extra suggestions I just listed didn’t scare you, you are seriously well under way to build good looking web sites. Pat yourself on the back, but make sure not to sprain your shoulder.

Conclusion

First and foremost: all of these have zillions of variations. Extra rules to make it work in other browsers, radial gradients, drop shadows in other directions or used for ’emboss’ effects, etc… For these, seriously and without shame:

Google for what you want.

… Seriously, just google for ‘CSS3 gradients’ or something, copy paste the huge ‘backwards compatible’ css rules they offer you in most code snippets, and then adjust the values in the code snippets to what you are exactly trying to achieve.

Ok, now that we’ve solidly entered into ‘modern’ terrain, let’s dial it up a notch and have a  look at the amazing power of JavaScript and jQuery.

Centering things with CSS

Often in CSS we want to center things, either vertically or – much more common – horizontally.  There are different types of centering we can do, and we will look at them separately.

Centering text

To center text within a container element, we use text-align:center, as follows:

<p class=”centeredtext”>This phrase will be centered</p>
<style>
.centeredtext { text-align:center; }
</style>

Which looks like this in the browser:

This phrase will be centered

Centering a block horizontally

To center a block element, like a div, horizontally, we use the margin:auto; property. More specifically, we want to make the left and right margins equal automatically. Note that obviously the element needs a width for this that is not the entire width of the page. Here is the code for a centered div element:

<div class="centeredblock">This block is centered.</div>
<style>
.centeredblock {
   background-color:#aaffaa;
  width:200px;
margin-left:auto;
margin-right:auto;
}
</style>

Which looks like this:

Screen Shot 2014-01-21 at 21.23.12

 

 

You can also center an image like this. But, centering only works with elements that have display mode ‘block’.  And the img element, by default, is not quite ‘block’. So you have to add a rule for that explicitly in css:

<img class="centeredimage">
<style>
.centeredimage {
display:block;
margin-left:auto;
margin-right:auto;
}
</style>

Centering a block vertically

To center a block vertically within another element, give the container element the display property ‘table cell’ and use the vertical-align:middle property, like this:

<div class="container">
  <p>This small paragraph...</p>
</div>
<style>
div.container { 
min-height: 10em; 
display: table-cell; 
vertical-align: middle
}
</style>

That said, actually, for images and text, you can also simply put it between <center></center> tags. But don’t tell anybody we told you that.

Linking to an external CSS style sheet file

So far, all the CSS code we have learned about, we put between <style> tags, like this:

<style>
 .myclass {
 background-color:#aaddcc;
 margin:10px;
 }
 </style>

In principle, it will work when you put your CSS anywhere in your HTML document, though the best way is to put them between your <head> and </head> tags.

However, there’s an even BETTER way: put your css code in a separate .css file, and link to that file from within your HTML document. This has several advantages:

  • It keeps your HTML files smaller and cleaner, with their own purpose (structure and content) nicely separated from the CSS with its own purpose (defining the layout). But mostly:
  • It allows you to use the same CSS code accross multiple pages (.html files). Since every web page beyond the most basic one will consist of multiple pages, this makes things a lot less complicated!

Linking to an external style sheet with the <link> tag

Quite analogous to HTML files, CSS files are just plain text files with the .css extension. So open a new document in your text editor and insert the following:

h1,h2,h3 {
color:red;
}
body { 
background-color:#aaffaa;
}

Note that there are no <style> or any other HTML tags needed here! Now, save this file with the name style.css in the same folder as your html file.

Next, open your HTML file, and insert this line in the header section (between <head> and </head>):

<link rel="stylesheet" type="text/css" href="style.css">

So if you started with the index.html file of our hello world lesson, the code should now look something like this:

<!doctype html>
<html>
 <head>
 <title>My first web page!</title>
 <link rel="stylesheet" type="text/css" href="style.css">
 </head>
 <body>
 <!-- actual content comes here -->
 <h3>Hello world!</h3>
 <p>
 This is my first web page, thank you for visiting it!
 </p>
 </body>
</html>

Now save your HTML file, and open it in the browser (by double-clicking on it). If you did everything correctly, you should see that the CSS rules are applied to your page like this:

Screen Shot 2014-01-21 at 13.39.29

Cool huh? From now on, always put your style definition in a separate .css file, and use the <link> tag to link to it.

Images in HTML with the img tag

After the hyperlink, the second most common HTML element is probably the image.

We specify an image with the self-closing <img> tag, with the – obligatory – src attribute pointing to the image location, like this:

<img src="https://www.google.com/images/srpr/logo11w.png" />

This will look as follows:

Similar to hyperlinks, the location of the image can be either an absolute URL that starts with http://&#8230; or a relative location that points to ‘internal’ files of the web site.

As the number of images for a web site can rapidly increase, it is a good practice to put images in their own folder. So your structure should look something like this (screenshot of Finder for Mac):

Screen Shot 2014-01-21 at 19.16.50

And you would then include two image in that index.html file as follows:

<img src="img/restaurant1.jpg" />
<img src="img/restaurant2.jpg" />

Image types to use for the web

Note that web browsers cannot display images of any file type. The file type of an image can be spotted by its extension, like .jpg in the above example. Make sure to always include the extension in the src attribute or the browser will not show it correctly.

The three types of images commonly used for the web are:

  • jpg: a ‘compressed’ image format, good for photos
  • png: another ‘compressed’ image format, which has a ‘lossless’ option. Good for complex graphics.
  • gif: the simplest and smallest format which has only very few different colors. Good for logos

Always be aware of the file size of your images: images that are too large will make your site too slow, especially in these days of mobile and tablet browsing!

Now that you know how to include images in your site, on to some text formatting: HTML typography!

Hyperlinks in HTML with the a tag

Two of the most important HTML elements are hyperlinks and images. Let’s have a closer look at these, since you’ll encounter them a lot.

Hyperlinks with <a href=”…”></a>

Just to make sure: by ‘hyperlink’, or link in short, we mean an element that causes the browser to navigate to a different web address (URL) when you click it. Like this: click me,I’m a hyperlink

To turn something into a link we use the <a> tag with the – obligatory – href attribute to specify where it should go, as follows:

<a href="http://www.google.com">click me, I'm a hyperlink</a>

To specify that the link should open in a new window/tab (the browser decides which one), use the target attribute:

<a href="http://www.google.com" target="_blank">I will open in a new page!</a>

To add a little hint what the link goes to when the user hovers over the link with the mouse, use the title attribute:

<a href="http://www.google.com" target="_blank" title="Go to search engine Google">Hold your mouse over me to see where I go!</a>

As you see, one HTML element can have quite a lot of attributes! But that’s ok, this happens all the time and is perfectly valid.

Relative and absolute, internal and external links

URLs tend to start with http://, and so that is what will typically come in the href attribute as well, like the http://www.google.com in the previous examples. Unless the web site you are working on is Google, in which they really made a bold hiring decision with a guy who visits sites targeted explicitly at idiots, this is an external link, i.e. going away from your website.

URLs that are specified ‘completely’ like that are also called absolute URLs.

However, the way a website – of the type we are learning to build here – works is, it consists of a large number of different .html files. At the very least one for each page of the web site. And those files contain links to the other files, for example a navigation menu is nothing else then a list of hyperlinks to different pages of the same site.

For these, we have relative URLs, when you link between ‘internal’ files that make up your web site. For example if you have 2 html files in one folder called page1.html and page2.html, you can put the following in the HTML code of page 2:

<a href="page2.html">to page 2!</a>

and this will work fine. You can even work with folders using the / character, as follows. Say your website folder contains an index.html file, and a folder named ‘pages’ which in turn contains some html files like page1.html, page2.html… Then you can link from within index.html to those as follows:

<a href="pages/page1.html">to page 1!</a>

You may want to open your file explorer and experiment with this! Can you guess in which situation you would use <a href=”../index.html”>?

Once you figured out the answer, or in 2016, whichever comes sooner, we will have a look at using images in your web site with the <img> element!

Specifying size and position with CSS

As you know, CSS is the language we use to ‘style’ our page (forgot? Check our CSS intro), i.e. define how all the elements should look exactly.

We will now have a look at one aspect of CSS: using it for defining size and positioning.

HTML Block versus inline elements

The browser views most HTML elements as belonging to one of two ‘display modes’: block elements and inline elements.

Block elements are elements that start (and end) with a new line when displayed in the browser. The main block elements are: <div>,<p> and <table>.

Out of these, <div> elements with a class or id attribute on them, and CSS rules setting their position and dimensions, are central to web design, since <div> is like the ‘template’ block element.

In the following site layout sketch, generously stolen from Jason Beaird’s  page on web anatomy), all the blocks will typically be divs with id of class attributes, and CSS defining their size and position:

layout-anatomy

Pretty huh? In many websites, those names of the block written next to them, are even exactly used for class and id attributes!

Inline elements are meant to fit in the ‘flow’ of the text, and the main examples are <a> for links, the typography elements of <strong> and <em> we saw earlier, and <div>’s stupid little brother, the generic <span> element, existing only to get a class attribute and be styled.

Setting height and width using CSS

Block elements like <div> are by default put on a new line, and have a width stretching all across the page. However, we can specify their size ourselves using the width and height rules. Sizes are typically represented in:

  • percentage (%) of their ‘container’ element (which is often the entire page) or
  • in pixels (px).

Here is the CSS we would use to create a ‘header’ block (not to be confused with the <head> tag in HTML) that stretches all across the page, and is 100 pixels high. There is only one header on the page, so we can use the id attribute rather than class:

<div id="header"><h1>Welcome to my awesome site!</h1></div>
<h2>What is love?</h2>
<p>Baby don't hurt me, don't hurt me, no more.</p>
<style>
#header {
width:100%;
height:100px;
background-color:#aaddff; /* let's make it blue to stand out */
}
</style>

This would look something like this in the browser:

Screen Shot 2014-01-20 at 19.03.44

Floating elements

Sometimes we don’t want a block to be entirely on its own line, but rather have the text going around it. We can achieve this by floating the element, using float:left; or float:right;.

Let’s get fancy and add a floating menu with some links to our code, and since I am writing this on MLK day, some more text to illustrate the effect. Lots of things going on here, study this well!

<div id="header"><h1>Welcome to my awesome site!</h1></div>

<div class="interestinglinks">
Interesting links:
<ul>
<li><a href="http://www.wikipedia.org">Wikipedia</a></li>
<li><a href="http://www.google.com">Google</a></li>
</ul>

</div>
<h2>I have a dream</h2>
<p>
I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
</p>
<p>
Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity.
</p>
<p>
But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself an exile in his own land. And so we've come here today to dramatize a shameful condition.
</p>
<style>
#header {
width:100%;
height:100px;
background-color:#aaddff; /* let's make it blue to stand out */
}

.interestinglinks {
float:left;
width:150px;
height:100px;
background-color:#ffffaa;
}
</style>

As you will see, things are looking real nice real fast:

Screen Shot 2014-01-20 at 19.16.07Conclusions

We have just started scratching the surface here, and positioning of elements with CSS is really quite an extensive subject, even more so since everybody and their mother started surfing  from their cellphone or tablet.

With your keen eye for design, you probably couldn’t help but noticing that the last example was kinda ugly because the text is crammed to the edges too much. Well observed, young grashopper!

We will see how to add some much-needed ‘breathing space’ to our elements in the next lesson about the CSS box model: margin, border and padding.

The CSS box model: margin, border and padding

All HTML elements can be considered ‘boxes’, i.e. rectangle areas that have some content in them. Also, still with the box analogy: boxes typically can be nested or  contained entirely within one another.

The way distances related to these boxes are calculated, and the terminology for each of these is called the ‘box model’. In the box, we have the content at the center, and then going outwards we have the padding, border and margin.

An image explains it best:

Screen Shot 2014-01-19 at 23.18.38

So, here is what we have:

  • Margin is space kept outside the box, separating it from other elements in the page.
  • Padding is the space kept inside the box, separating the content from the edge.
  • Border is, well, how fat or thin (or non-existing) the border around the box is.

Each of padding, border and margin can be specified using CSS rules. They are most often specified in pixel, or px.

Specifying box measures for all directions or just for one

If you want some more space around an element, you give it more margin, like this:

margin:5px;

However, what if you want just some more space on the left of the element? Or just above or below it? To do this, you can specify the margin just for the top, right, bottom or left. So, for some more space below an element we would add bottom margin like this:

margin-bottom:5px;

The same goes for padding. So for example, to specify to leave some space between an elements top and bottom edges and the content within it, you would specify like this:

padding-top:5px;
padding-bottom:10px;

Margin and padding in action

Feel free to open up your text editor and follow along!

Let’s start with 2 div elements, and give them each a border and a different background color:

<div class="mybox">This is some text</div>
 <div class="mybox">This is some other text</div>
 <style>
.mybox {
background-color:yellow;
border:4px solid black;
}
 </style>

Here is how that looks in a browser:

Screen Shot 2014-01-19 at 23.51.05

The boxes are stuck together, so let’s add a little space around each box. Add a margin rule to the CSS, so it becomes this:

<div class="mybox">This is some text</div>
 <div class="mybox">This is some other text</div>
 <style>
.mybox {
background-color:yellow;
border:4px solid black;
margin-bottom:5px;
}
 </style>

This gives some nice space between our boxes:

Screen Shot 2014-01-19 at 23.50.43

Finally, that text in there looks rather ‘cramped’, i.e. too close to the edges. It’s good practice to give elements some ‘breathing space’ by adding padding to them. So let’s have one last change to do that, like this:

<div class="mybox">This is some text</div>
 <div class="mybox">This is some other text</div>
 <style>
.mybox {
background-color:yellow;
border:4px solid black;
margin-bottom:5px;
padding:10px;
}
 </style>

… And here’s how that looks:

Screen Shot 2014-01-19 at 23.50.28

… And that’s it! A lot more ‘breathing room’ for our content now, which is what is important in any well-designed web page!

Conclusions

You want to really, really internalize the concepts of the ‘box model’ because they are super duper important in web design.

  • Margin – space at the outside of an element
  • Padding – space at the inside of an element