Day 4 of the CareerFoundry Web Development Short Course

Create: 2018-06-14
Update: 2018-06-15
Score: 0
Safe: Yes

Outbound domains: email.careerfoundry.com |
Email_Header_WEB_DEV_Short_Course_Day_04.jpg

Day 4 - CSS Layout & Box Model

Welcome to the fourth day of the Web Development Short Course!

You’ve made it halfway through the course. Well done! Remember yesterday? We went over the different basic HTML tags and created a page from scratch. We left that page unstyled, not very attractive to the human eye, yet very readable--especially for the browser.

 

If you want to find out how 1-on-1 tutoring can help bring your code to the next level book a free call with a Career Advisor.

 

What are we doing today?

Today we’ll be focusing on styling this page by playing with the different options that the div boxes offer for margins, sizing, padding and positioning.

First, we’ll have to reset the default behavior in order to have the basics to start building our styles. Second, we’ll be playing around with the different display properties of blocks, as well as the positioning thereafter. Then we’ll dive deep into the box model to adjust the padding, margin, widths and borders of our boxes with the use of the Developer Tools.

Our goal is to make your page look something like this:

Day4-Img1.jpg

Adding Basic CSS Stylesheets

Drag your entire project folder into Sublime Text to open it there. To set up your workspace, open 'about.html'. Then, open up 'styles.css' in another tab. Hit Command + Option + 2 to make two columns, and drag one of the tabs over to the second column so you can see both files at once.

To style this page, we need to link some CSS files. Technically it is bad practice to have separate CSS files for different pages. Having only a single styles.css file will let your page load faster. It also keeps your stylesheets all in one place so you don't need to have copies of the same code in several different CSS files. Since we are learning how to create a web page from scratch now, though, we are going to make an exception and keep our new code separate from the other file.

In your project’s CSS folder, make a new file called about_styles.css. In the head part of your HTML file, after the meta tag, use <link> tags to attach about_styles.css to your file. Go back to Lesson 2 if you forget how to do this.

Open 'about.html' in Chrome. Open dev tools (Command + Option + I). Click the magnifying glass at the top left of your dev tools panel and click on an element, such as a header or paragraph of text. Alternatively, on your website, right click on an element and click on "Inspect element." In the “Styles” (right) column of dev tools, scroll down to see the box model diagram.

Day4-Img2.jpg

Don't worry if you don't understand what any of this means yet.

The first thing you should know about web pages is that every element is a box. It may not look like one, but it is a box. Don’t believe me? Add the following line of code to the top of about_styles.css and then refresh:

* { border: 1px solid red; }

The asterisk * is the universal selector. It’s what we use when we want to affect everything, every individual element on your website.

Ok, now remove this line; we won't be using it as part of our design.

As you examine the elements on your page and the way they are highlighted by dev tools, you can see that, even though this is unstyled HTML, the elements do have certain style characteristics, especially margins on the top and bottom.

Where do they come from?

Well, since not everyone is a styling ninja like you and I, the browser has something called a user agent stylesheet. It’s a built-in CSS stylesheet that’s there to make sure things don’t look completely horrible even if someone adds no styles at all or the CSS fails to load for some reason. Scroll up in the “Styles” column and you’ll see the user agent stylesheet.

Day4-Img3.jpg

Some of these built-in styles are going to cramp your style as you move forward. Some browsers actually have slightly different built-in styles than others. So, to make sure our website looks exactly how we want in all browsers, we are going to include another CSS stylesheet to override several of the built-in styles.

The two best-known stylesheets that do this are normalize.css and reset.css. We prefer Normalize, which keeps some default styling, changes some, and gets rid of some. Bootstrap already has normalize.css included. But since, for now, you are not using Bootstrap, go ahead and download the normalize.css file from here. (If it is displayed in your browser instead of downloading you can just right click somewhere on the page and then click on "Save as"). Save the normalize.css file in the css folder of your project. Go ahead and link it up, before about_styles.css.

Remember, style sheets are cascading, so the last stylesheet you add will be the one that gets applied in case of a conflict between style definitions.

Now that you removed any unnecessary styling from the user agent stylesheet, the default stylesheet included by the browser, we can start from a “normal” slate!

CSS selectors

CSS is always set up the same way. First you select an element with what's called a "selector." Then, between curly braces that look like this: { } you add properties and values to the CSS rule to style the element you selected in a certain way.

There are several different ways to select HTML elements:

  • HTML tags: To select all HTML tags of a certain type, simply write the name of the tag in the selector like this: div {} or this: h1 {}
  • Classes: To select classes, you use a dot in front of the class name like this: .container {}
  • IDs: IDs are selected with a hashtag: #greatId {}
  • Descendants: Often times you want to select all elements that are descendants of another element. For example to select all <p> elements that are in another element with the class .classname you would write in CSS: .classname p {}. Notice how there is a space between the two selectors. That means that your code will look for all p elements inside .classname -- no matter if the p elements are direct descendants of .classname or if they are inside another div within it. You can even select p elements which are inside another div element which is itself inside an element with the class .classname. That would look like this: .classname div p {}
  • Direct Descendants: While a space between selectors will cause your code to select all elements inside the first one, the direct descendant selector > will only select the direct children of an element. For example this selector .classname>p {} will select this p element:

<div class="classname">
  <p>Hello</p>
</div>

but not this one:

<div class="classname">
 <div>
   <p>Hello</p>
 </div>
</div>

because there is another div element between .classname and p

  • Attributes: You can even select HTML elements by their attribute (with or without value) using square brackets. [href] {} will select all elements with an href attribute. [href="http://google.com"] will only select those elements that have an href attribute and the value http://google.com

There are many more selectors. You can find a full list on w3schools or on this guide of the 30 most useful selectors.

LISTING SELECTORS

It is possible to add multiple selectors to the same rule. You do that by separating them with commas. You can list any type of selector. Even descendants: .classname, h1, div p {}

Styling with CSS

Let’s add some space on either side of your content. In your about.html, you put all your page content in a div with the class container. Now, in your about_styles.css file, make container take up 80% of the horizontal space on the page, instead of all of it, and center it, with the following code:

.container {
   width: 80%;
   margin: 0 auto;
}

We added the width in a percentage rather than pixels to allow for flexibility in screen sizes. As more of the web is moving towards various screen sizes, we recommend using percentages to allow for fluid layouts.

“margin” applies spacing around your HTML element.

The two CSS properties margin and padding take either one, two or four parameters. Here we have two: 0 and auto.

If you have four parameters (e.g. like this: margin: 10px 0 20px 5px;) then the four parameters are going to apply to the four sides of your box in this order: top right bottom left.

If you only have two parameters (like in our example) the first value (0) corresponds to top-bottom of the element. The second value (auto) corresponds to left-right.

If there is only one parameter (margin: 20px;) it will be applied to all four sides.

Review

Remember, that’s called a CSS rule. It consists of a selector (a class, in this case) and a declaration block enclosed in curly braces. It contains property-value pairs, each of which must be followed with a semicolon. The dot in front of "container" lets your CSS know it’s a class and not some other type of selector. This div will have a width of 80% of the page, with margins automatically adjusted accordingly to keep it centered. Save your CSS file. Refresh your about.html page and see it work. Click on it with your dev tools magnifying glass to see this rule at work.

Layout: CSS positioning

Nice job with the first step of your page layout! Now, let’s center the main heading (h1) of your page. Since we could potentially have an h1 elsewhere that we don’t want centered, we will make sure to refer to the one inside the div with class “header”. We can nest the selectors like so to achieve this:

.header h1 {
   text-align: center;
}

As you might guess, alternatively you can also align your text to the right or left of your page.

Positioning

There are 4 types of positioning in CSS you can use with the syntax:

selector {
   position: relative;|
}

  • Static is the default positioning. The element is in the flow of document. That is, elements will appear one after the other in the order they're listed in your HTML file. Properties like left, right, top, and bottom have no effect.
  • Relative positioning means the element is where it would normally be in the flow of the document, but you can change its position with properties like left, right, top, and bottom.
  • Absolute positioning places the element at an exact location on the screen with regard to its parent element, which is usually <html> or a container div. It can be defined with top, bottom, left, and right. The values express distance from the top, bottom, left, or right edge of the parent element.
  • Fixed elements are like absolute, but they are defined relative to the browser window, so they stay in the specified position even when the user scrolls. Fixed position is used to keep things like sidebar navigation or footers in place.

Layout: Display

Check out both your image and the div called “intro” in your dev tools. You can see that even small content takes up the whole width of the page. That’s because its default CSS display property is set to display: block; find where that’s being set in the “Styles” column of your dev tools.

Day4-Img4.jpg

There are different options to display an HTML element:

  • block means an element takes up the whole width of the parent HTML element and lets nothing be next to it on the left or right. Take a look at the following example:

<style>
 p {
   display: block;
}
</style>

<body>
 <p>I am some text</p>
 <p>and I am even more text</p>
</body>

The above example will look like this:

I am some text
and I am even more text

  • inline will put put two elements in a single line of text. Even adding margin and padding at the top and bottom of the element will not knock it out of line. Elements that are meant to sit seamlessly in text, like <span>, have a default display value on inline. So if in the above example we change our styles to look like this:

p {
 display: inline;
}

our page will look more like this:

I am some text and I am even more text

  • inline-block works very similarly. However, it will not line up the content of both elements in line. Instead it will treat both elements as individual boxes and put those in line. The top and bottom margin and padding of an element will definitely affect an element's position if you use inline-block.

By default <p> and <div> elements are displayed as blocks. So they are going to take up the full width of your page. You can change that behavior in your CSS with display or float.

Now let’s make our introductory content sit alongside the image. Set the display property for .image and .column to inline-block and see what happens. Better, right?

.image {
     display: inline-block;
}

.column {
     display: inline-block;
}

But we want the text in the columns to line up with the top of the image. Let’s set them both to:

float: left;

Float is a positioning property. It will move all your content to one side and the rest of the content "float" around it. You can use it for example to overwrite the default behavior of a div element to take up the full width.

Now the paragraph below is running into our introductory text and image! We never want it to do this. So let’s make a new CSS rule for the main-text class. Make it clear: both;. Clear is a property that says whether floating elements are allowed to be next to this element or not. Now we’re closer to the layout we want.

.main-text {
       clear: both;
}

Let’s make sure these columns are the same size. First go ahead and add the class column also to the div element with the class image. Now give .column a width of 30%. That’s 30% of the container. (Remember: if you use percentages on width or height it will always refer to the width or height of the parent element.) Now we should have three evenly sized columns. (If your image is larger than the other columns don't worry. We are going to take care of this in just a minute.)

.column {
     width: 30%;
}

This content looks weirdly crowded. Let’s start by adding padding-top: 60px to main-text. Padding and margin: they’re different.

Padding goes inside an element, making space around the text or other content that the element has.

Margin makes space between an element and the elements around it.

Their syntax is similar: you can specify padding-top, padding-right, padding-bottom, and padding-left as separate properties, or you can write them in one line, in this order (like with the margin above):

padding: top right bottom left;

Remember: A single value for padding (like padding: 40px;) means you’re assigning that value to all four sides. Two values (padding: 10px 50px;) means the first is top/bottom while the second is left/right.

BOX MODEL

If you are still not really sure how padding and margin works, check out this interactive demo of the box model. The colors you see are also the same, that are used in Chrome Developer Tools to visualize the different properties.

Play around with it a little bit until you are familiar with how the box model behaves.

Select your header div using your magnifying glass in dev tools. Note the first panel of your Styles column: element.style.

Day4-Img5.jpg

Try adding a margin-bottom of 40px. Watch it get applied. Play with CSS properties until you’re happy, then copy and paste them into your stylesheet to make them stick.

Give the text in these columns some breathing room. Add padding: 0 20px; to column. Oops — it makes the divs too big and knocks them out of alignment. But if padding is on the inside of an element and margin is on the outside, you would think that if you specified a width for your element, as we did, padding would not affect that width. Not so! Padding and border both make your element bigger. So, we add this to the top of our stylesheets:

* { box-sizing: border-box; }

Remember, * is the universal selector. You are applying this rule to every element in your layout. Now the box model will work in a way that makes more sense: Padding and border will not affect an element’s size if you’ve specified one.

CSS Dimensions and Units

With the dimension properties height and width you are able to set the dimensions of any HTML elements on your website. We have used it before to declare our columns to only take up 30% of the width of their parent element (in our case that's the div with the class container).

Dimensions are most commonly defined with one of the following two units: Pixel px or percentage %.

Pixels are absolute units and used if you want to specify an exact dimension (people often times do that for example with the top navigation of a website).

Percentage relates always to the parent element. So let's take a look at the following example:

<style>
 div {
   width: 100px;
}

 p {
   
width: 50%;
}
</style>

<div>
 <p> Hello World! </p>
</div>

<p> This is the second paragraph </p>

The first p element, that contains "Hello World!" will be 50% of the width of the div it is in. This means it will be 50px wide.

The second p element at the bottom of the code however will take up 50% of the full width of the whole page and likely be much bigger.

Now with that knowledge let's make sure our image is displayed correctly and does not mess up our layout. Give your <img> tag a class of your choice and in your about_styles.css write a new CSS rule for that class and give it a width of 100%. This will cause your image to automatically take up the full width of the 30% column you created before.

Notice, how the height is automatically adjusted? Since we didn't specify any height it is automatically set to auto.

Liv no background.png

Congratulations!

Day 4 completed. Learn more about a career in web development by talking to a Career Advisor today.

 

Well done! By now, you must be seeing the web a bit differently, you realise all elements in all webpages are rectangles, boxes. All of these elements have padding sizes, margins and different position settings. All of these giving us the possibility to organise our blocks in a way that each of them has their own space. You see how resizing a page can lead to changing the size of certain elements and not others? That is the use of percentages and fixed pixel sizes.

Tomorrow, we’ll be playing with the different colors we can use in CSS and how to style the fonts in different ways. The font weight, sizing, text alignment and many others. We’ll also be including web fonts and custom fonts! See you tomorrow!

William at CareerFoundry

Connect with CareerFoundry

© CareerFoundry GmbH | Köpenicker Straße 126 10179 | Berlin | Berlin | Germany

Registration/Handelsregisternummer: HRB 155933 B, AG Charlottenburg
VAT number/Umsatzsteuernummer: DE294024931
Managing Directors/Geschäftsführer: Raffaela Rein, Martin Ramsin

Unsubscribe

Want to protect your real email from messages like this? Use TempM email and be more secure on the internet.