Start learning with our library of video tutorials taught by experts. Get started

CSS: Core Concepts
Illustration by

Controlling element spacing


From:

CSS: Core Concepts

with James Williamson

Video: Controlling element spacing

We'll start exploring the individual properties of the Box model by taking a closer look at the margin property. Margins help us control the spacing between elements and can be specified individually for the top, right, bottom, and left sides of an element. While on the surface margins appear to be pretty simple. There are some very complex rules associated with calculating how margins are applied. So let's take a closer look at that. I have the element-spacing.htm file open and you can find this in the 05_02 directory.
Expand all | Collapse all
  1. 4m 57s
    1. Welcome
      55s
    2. Using the exercise files
      4m 2s
  2. 1h 7m
    1. Exploring default styling
      4m 56s
    2. CSS authoring tools
      2m 29s
    3. CSS syntax
      4m 45s
    4. Writing a selector
      4m 10s
    5. Setting properties
      8m 40s
    6. Common units of measurement
      7m 47s
    7. Inline styles
      5m 1s
    8. Embedded styles
      5m 19s
    9. Using external style sheets
      10m 34s
    10. Checking for browser support
      8m 48s
    11. Dealing with browser inconsistencies
      5m 30s
  3. 2h 15m
    1. Structuring HTML correctly
      2m 51s
    2. Element selectors
      4m 52s
    3. Class selectors
      6m 4s
    4. ID selectors
      3m 27s
    5. Using classes and IDs
      10m 7s
    6. Element-specific selectors
      4m 35s
    7. The universal selector
      5m 42s
    8. Grouping selectors
      4m 49s
    9. Descendent selectors
      7m 32s
    10. Child selectors
      5m 7s
    11. Adjacent selectors
      5m 30s
    12. Attribute selectors
      12m 43s
    13. Pseudo-class selectors
      3m 54s
    14. Dynamic pseudo-class selectors
      8m 29s
    15. Structural pseudo-class selectors
      6m 45s
    16. Nth-child selectors
      13m 10s
    17. Pseudo-element selectors
      12m 40s
    18. Targeting page content: Lab
      8m 56s
    19. Targeting page content: Solution
      7m 59s
  4. 42m 39s
    1. What happens when styles conflict?
      4m 0s
    2. Understanding the cascade
      5m 47s
    3. Using inheritance
      6m 11s
    4. Selector specificity
      6m 55s
    5. The !important declaration
      4m 5s
    6. Reducing conflicts through planning
      3m 33s
    7. Resolving conflicts: Lab
      6m 45s
    8. Resolving conflicts: Solution
      5m 23s
  5. 1h 47m
    1. Setting a font family
      7m 10s
    2. Using @font-face
      9m 18s
    3. Setting font size
      7m 35s
    4. Font style and font weight
      6m 52s
    5. Transforming text
      3m 58s
    6. Using text variants
      2m 49s
    7. Text decoration options
      4m 26s
    8. Setting text color
      3m 2s
    9. Writing font shorthand notation
      8m 49s
    10. Controlling text alignment
      6m 33s
    11. Letter and word spacing
      9m 11s
    12. Indenting text
      4m 30s
    13. Adjusting paragraph line height
      10m 30s
    14. Controlling the space between elements
      6m 41s
    15. Basic text formatting: Lab
      8m 45s
    16. Basic text formatting: Solution
      7m 14s
  6. 2h 1m
    1. Understanding the box model
      16m 53s
    2. Controlling element spacing
      14m 29s
    3. Controlling interior spacing
      10m 49s
    4. Margin and padding shorthand notation
      6m 27s
    5. Adding borders
      8m 57s
    6. Defining element size
      10m 7s
    7. Creating rounded corners
      6m 58s
    8. Background properties
      2m 51s
    9. Using background images
      5m 10s
    10. Controlling image positioning
      10m 25s
    11. Using multiple backgrounds
      7m 5s
    12. Background shorthand notation
      5m 25s
    13. Styling container elements: Lab
      7m 55s
    14. Styling container elements: Solution
      8m 17s
  7. 47m 51s
    1. Color keyword definitions
      5m 4s
    2. Understanding hexadecimal notation
      6m 5s
    3. Using RGB values
      4m 58s
    4. Using HSL values
      5m 17s
    5. Working with opacity
      2m 23s
    6. Using RGBa and HSLa
      3m 8s
    7. Styling drop shadows
      5m 38s
    8. CSS gradients
      6m 32s
    9. Working with color: Lab
      4m 26s
    10. Working with color: Solution
      4m 20s
  8. 1m 58s
    1. Additional resources
      1m 58s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
CSS: Core Concepts
8h 49m Beginner Nov 22, 2011

Viewers: in countries Watching now:

In this hands-on course, James Williamson demonstrates the concepts that form the foundation of Cascading Style Sheets (CSS), including styling text, adding margins and padding, and controlling how images display. The course also explores the tools needed to work with CSS, the differences between embedded and external styles, how to use selectors to target elements, and what to do when styles conflict.

Topics include:
  • Exploring default styling
  • Writing a selector
  • Setting properties
  • Working with common units of measurement, including ems and pixels
  • Structuring HTML correctly
  • Understanding the cascade and inheritance
  • Setting a font family, font size, text color, and more
  • Understanding the box model
  • Styling container elements
  • Working with RGB vs. HSL values
  • Styling drop shadows
Subject:
Web
Software:
CSS
Author:
James Williamson

Controlling element spacing

We'll start exploring the individual properties of the Box model by taking a closer look at the margin property. Margins help us control the spacing between elements and can be specified individually for the top, right, bottom, and left sides of an element. While on the surface margins appear to be pretty simple. There are some very complex rules associated with calculating how margins are applied. So let's take a closer look at that. I have the element-spacing.htm file open and you can find this in the 05_02 directory.

I just want to go ahead and Preview this in the browser so you guys can see kind of what's going on in this file, because it looks a little different than some of the ones we've used before. When I open it in this browser, you guys can see what I am talking about. So we have this sort of grid on the page, and that's essentially just sort of a background graphic applied to the HTML tag, and that's going to allow us to sort of visualize how these elements are spacing apart from one another. I am going to go back into my code and I want to go over the page structure really quickly here. We have two headings, they have classes applied to them, 1 and 2, so object 1, object 2, and then we have two div tags, the first div tag has a class of three, so it's a third object, and then our second div tag has a class of four.

Now, both of those div tag have elements inside of them as well, and margins within nested elements can really cause some problems in terms of how to calculate those. So we're going to use these interior elements, these two paragraphs in the first div tag and the single paragraph in the second div tag to sort of play around with how nested elements and margins work together as well. If I scroll up into my styles, you can see we have placeholder selectors for the three and four elements. And if I go up a little bit further I can see that I have a group selector for one and two and then another one that's empty just for two.

But the styling on this one and two are creating those sort of boxes that you guys saw and then positioning them side- by-side to the use of this float. Okay. Well, let's take a look at how horizontal margins work. If I go to this group selector, the one and two here, I am going to go ahead and create a margin-right property and I am just going to go ahead and give it a right margin of 60 pixels. So as far as syntax goes, when you're declaring a margin, you can just say margin- and then the side you want to apply it to, so that would be top, right, bottom, or left. In this case, I am giving it an absolute value of 60 pixels.

So I am going to go ahead and Save this and then go back to my browser and Refresh this and you can see that I am getting exactly 60 pixels worth of space between those two. So these gridlines are about 10 pixels long. Now, what's interesting is I do have 60 pixels worth of margin out to the side of this one as well, you just can't see it, because there's really nothing out there, but if it ever runs into something, that margin would affect the object that it touches. So right now we just have right margin applied, so the margin is pushing out this way. What if we added some left margin to the second object? If I go back into my styles and I go to number two, I can go in here and say margin-left, and let's go ahead and give it a left margin of 20 pixels and we'll go ahead and Save that.

Now, when I preview this, I can see that we do have that added spacing, it's cumulative, so we have 20 pixels of margin coming from this side, we have 60 pixels of margin coming from this side, and all total that gives us 80 pixels of spacing between it. So when you're dealing with horizontal margins, you have to be aware of whether those margins are coming from both the right side and left side or just one side or the other in order to really understand how much spacing there's going to be between those two elements. Now, vertical margins react entirely differently.

So let's take a look at what vertical margins do for us. I am going to go back to my code and in this number one and number two selector, I am going to add another line, and in this one I am going to say margin-bottom: 20px So if I Save that and I test it, at first glance, it looks almost exactly the same. We have a little bit of an offset on the grid here, so it's an offset by about 5 pixels, but I think you can see what the gridlines are doing for us here. That's 20 pixels worth of space between these elements and the elements below them, so that's kind of exactly what I was thinking that we would get.

However, what I want to do is I want to go to the first div tag, remember the first div tag is right underneath the headings, and its class is 3, and I am going to give that a margin-top value. And let's go ahead and give it a margin-top of 40 pixels. So we have 20 pixels coming from the bottom of these headings, which are floated elements above it, and then margin-top of 40 pixels of the div tag below that. So I am going to Save this and I am going to test it. If this was behaving exactly the same way as our horizontal margins, we would now have 60 pixels worth of margins between them, but we don't.

As a matter of fact, no change occurs whatsoever. Now, there are multiple reasons of why vertical margins don't combine with each other and there are multiple things that trigger that. In this case, it has nothing to do with what we're going to look at in just a moment, which is called vertical margin collapse. In this case, it has everything to do with the fact that these two elements right here are floated elements. Floated elements are removed from normal document flow. What that means is everything else sort of moves up to take its place. So essentially the margin, this 40 pixels worth of margin here on this div tag, it's really sort of floating up and going up underneath those objects; the 20 pixels of margin is indeed pushing down, and it's one of those really weird things that you have to deal with, with floated elements, because these elements down below have what's known as a clear property applied to them.

So really in order to truly understand that, you have to understand floats, and floats is not something that we're going to talk about in this title, I will talk about floats in great detail within the title that's going to follow this one, which is the CSS Page Layout title. So we will definitely come back to floats. For now though, I want to take a look at another way that vertical margins interact with each other when they touch. So I am going to go back into the code and what I want to do is I want to go to my paragraph selector because, remember, we have two paragraphs inside the first div tag and we have another paragraph inside the last div tag.

So if I go up to my paragraph, I am just going to create a new line in that and I am just going to say margin-top, and let's just do 20 pixels; nice even number. So we'll Save that, preview it, and now we're seeing a little bit of extra spacing here. Now, if you're wondering what this color is, that is the background color of that div tag. We can now see this, because these paragraphs are no longer touching each other. So the sort of blue color is the background color of the paragraphs, whereas the purple color is the background color of the div tag.

So we're getting 20 pixels worth of spacing here, we're getting 20 pixels worth of spacing here. So it looks okay right now, but currently all we have going on is a margin-top, what if we combine this with a margin bottom, what would happen then? So let's go back into our code, and what I am going to do is right here still in the paragraph selector, I am going to do a margin-bottom of 20 pixels as well. So above each paragraph we'll have 20 pixels worth of margin and below each paragraph we'll have 20 pixels worth of margin as well.

So if I test this, absolutely nothing happened. Believe it or not, that's not broke, that is the way it is supposed to happen. We have 20 pixels pushing up here, we have 20 pixels pushing down here, we have 20 pixels pushing up here, we have 20 pixels pushing down here, so why don't we see that space? Well, that is due to something that we call vertical margin collapse. That can be sort of summarized in a nutshell by saying that when two vertical margins touch each other, when they touch, they collapse, and essentially if their values match, you just get what one of the values is, if their values are mismatched, you get the larger of the two values.

That doesn't sound very intuitive until you think about how paragraph spacing works. If vertical margins didn't collapse every time you used a paragraph, you would get double spacing between that paragraph instead of single spacing. So there's a very good reason for vertical margin collapse to exist. Let's take a look at how we can sort of take advantage of that. So I am going to go back into my code, and now what I am going to do is go into the paragraphs and I am going to give them a bottom-margin of 30 pixels now instead of 20 pixels. So when I Save this and test it, notice that we do get the increase by 10 pixels.

So when two values are touching each other, the larger of the two values are used, in this case, 30 pixels rather than 20 pixels. Vertical margin collapse is pretty easy to understand when you have two elements that follow one right after the other. We've got one paragraph on top of another paragraph, we know that margins inside that is going to collapse, that's pretty easy to keep track of. However, when you have nested elements inside of other elements, it can be a little bit tricky. So let's see how vertical margin collapse works when you have parent elements and nested elements inside of them that both have margin values.

So going back into my code, just so that we can sort of remember the structure that we have here, we have these two div tags, three and four, and currently three has a margin-top of 40 pixels, but four doesn't really have anything going on into it. In three, I am going to go ahead and modify that and do a margin-bottom of 20 pixels, and then for the four selector, I am going to go ahead and do a margin-top of 20 pixels. So if I Save this, now those two div tags should be touching each other as well.

So again, knowing what we know about vertical margin collapse, we would expect to see only 20 pixels between them. So I am going to Save this, test it, and I don't see any movement between them at all. Now, the reason we don't see any movement at all is remember they have paragraphs inside of them and those paragraphs have margins as well. Remember that the paragraph's bottom- margin value is 30 pixels, which is higher than either of those, so it's the 30 pixel value that's used. Essentially when you have elements that touch each other or even nested elements, if there's nothing to keep the vertical margins from touching each other, meaning there's no border there, there's no padding there, there is just content, then all those vertical margins collapse; outer element's vertical margins collapse and the inner element's vertical margins collapse.

If you have a paragraph that's empty, its top and bottom margin collapses in and of itself, which allows empty paragraphs to not take up any space. So you have to remember all of those things when you're dealing with element spacing. If you look at this, we really should have about 90 pixels between these two if we didn't have any vertical margin collapse, because we have the 30 pixels worth of margin on the bottom paragraph, we have the 20 pixels worth of margin on the bottom div tag, we have the 20 pixels worth of top margin on the div tag, and we have the 20 pixels worth of margin on the paragraph.

So that should give us around 90 pixels. But because they collapse, they collapse down to the highest value of those, which would be 30 pixels. I mentioned that this happens because there is nothing to keep the vertical margins from touching each other, but what if there is? So the last thing we're going to do, let's go back in and let's prevent some of these margins from touching each other and see what happens then. So in the three element, I am just going to come in and apply a border to it. So I am just going to say border: 1px solid black; so just black for color.

On the before, I am not going to use border, I am going to use padding and I will just do a padding of 1 pixel, then we'll Save that. Then when I Preview this in the browser, now we're seeing a lot of those margins come into play. We're seeing the margins now on this paragraph that aren't collapsing anymore, we're seeing the 30 pixels on the bottom, we're seeing the 20 pixels on top, because the padding, that 1 pixels worth of padding all the way around our div tag, is causing that margin to stop when it reaches the padding. We now only get 20 pixels between the div tags, because their margins are collapsing, but we still see the 30 pixels worth of margin here below the paragraph; 20 pixels above it, because that border now is stopping those margins when they touch.

So when you're dealing with vertical margins, especially dealing with the collapsing of vertical margins, you also have to keep in mind that borders and padding can interrupt that collapsing, keep margins from touching, and then give you the spacing that you're expecting, or in some cases result in unwanted spacing that you have to deal with, so that is definitely part of the vertical margin collapse that you need to be aware of. I want to pass along one more piece of information. I know we've gone over a lot in this lesson, but I want to talk about a very unique ability that margins have, and that is the ability to use the auto value.

So if I go back into my code, I am going to go down to four here. I am just going to create a new selector. I am going to target the paragraph inside of that div tag; so .four p and then inside of that what I am going to do, I am going to give the paragraph a width of 80%. So that's telling you, hey, take up 80% of the available space inside this div tag. And then below that I am going to say margin-right: auto and margin-left: auto So what auto is, that auto value is basically telling the browser, give me whatever is left over.

So think about the way that this is working. If I am telling my paragraph, hey, only the 80% in terms of width of your parent element, and then right, give me whatever is left over and, left, give me what is left over, it's going to calculate those values and then split them evenly on the left side and the right side. What does that do for us? Well, if I Save the file, and test this in the browser, you can see it centers the paragraph horizontally within that div tag, and that actually is exactly how I am centering the body content on this page.

It's a very common technique. A lot of people use the auto-margin centering technique, but what's really nice to know about margins is that we have that ability to say auto, in which case it's going to take whatever value is left over from the width of an element and go ahead and apply the margin to that. But if you take anything away from this, margins control all of our element spacing. Vertical margins, those can be very, very tricky. If you had trouble with the vertical margins, because I know that I threw a lot at you there, and if you didn't get all that the first time around, just watch this movie over a couple of times and do the exercise again a couple of times.

The more you work with vertical margins, the more comfortable you'll get with understanding when they collapse and when, like in our floated elements up here, they're ignored. And I can't stress to you how important this is. Trust me, without understanding how margins work, trying to style containing elements and control page layout becomes extremely difficult. So this is definitely a concept that you're going to need to put in the proper amount of time to master it.

There are currently no FAQs about CSS: Core Concepts.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed CSS: Core Concepts.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Notes cannot be added for locked videos.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.