Module 13: The CSS Box Model

Introduction

Understanding the Box Model in CSS

Welcome to the foundational concept of CSS layouts – the Box Model! It's an essential concept that will revolutionize the way you see and style HTML elements. Every element in a web page is a box, and understanding this box is key to precise control over layout and design.

The Anatomy of the Box Model

At its core, the CSS Box Model consists of four parts: margins, borders, padding, and the content itself.

  • Content: This is the area where your text, images, and other content reside.
  • Padding: The space between the content and the border. It increases the area around the content within the border.
  • Border: A line that wraps around the padding and content. It's the edge of the element as seen by the browser.
  • Margin: The outermost layer, creating space between the element's border and surrounding elements.\

Box Model in Action: A Practical Example

Let's apply the box model to a simple HTML <div> container. Consider this HTML snippet:

<div class="styled-box">Hello, Box Model!</div>

Now, let's style it with CSS:

.styled-box {
width: 200px;
padding: 20px;
border: 5px solid black;
margin: 30px;
background-color: lightblue;
}

In this example, we have:

  • Set the width of the content area to 200px.
  • Added 20px of padding around the content, increasing the box's size while keeping the content at 200px wide.
  • Defined a 5px solid black border around the padding.
  • Added a margin of 30px, creating space between this box and other elements.
  • The background-color is applied up to the border, but not the margin.

Box Sizing: Controlling the Box Model

By default, the width and height you set apply only to the content, not the total size of the box. This can be changed with the box-sizing property:

  • content-box (default): Width and height only apply to the content. Padding and border are added outside.\
  • border-box: Width and height apply to the content, padding, and border. The margin is still added outside.

Let's modify the previous example to include box-sizing:

.styled-box {
width: 200px;
padding: 20px;
border: 5px solid black;
margin: 30px;
background-color: lightblue;
box-sizing: border-box;
}

With border-box, the total width of the box remains 200px, including padding and border.

Conclusion

The Box Model is the cornerstone of layout design in CSS, providing a clear understanding of how elements are structured and spaced. As you experiment with different properties of the box model, you'll gain a deeper appreciation for the precision and flexibility it offers in web design. Let's embrace the box model and create web pages with layouts that are both beautiful and meticulously crafted!



Styling Basic Containers with CSS

Dressing Up <div> and <span>: The Basics of Container Styling

Welcome to the heart of web aesthetics! In this section, we're going to explore the essentials of styling two of the most commonly used HTML containers: <div> and <span>. Through CSS, these basic building blocks transform into visually appealing elements that enhance your web design. Let's start styling!

Styling the <div> Element

The <div> element is like a canvas in web design – it can become anything you want. Being a block-level element, it's perfect for creating sections, boxes, and layout divisions. Let's see how we can style a <div>:

HTML Structure:

<div class="info-box">This is an info box.</div>

CSS Styling:

.info-box {
background-color: lightcoral;
border: 2px solid black;
padding: 10px;
margin: 15px 0;
width: 50%;
}

In this example, the <div> with the class info-box gets a background color, a solid border, some padding around the content, a margin for spacing from other elements, and a width of 50% of its containing element.

Styling the <span> Element

The <span> is an inline container, perfect for styling smaller chunks of text or inline elements. It doesn't start on a new line and takes up only as much width as necessary.

HTML Structure:

<p>This is a <span class="highlight">highlighted</span> text in a paragraph.</p>

CSS Styling:

.highlight {
background-color: yellow;
font-weight: bold;
}

Here, the <span> with the class highlight makes the text background yellow and the font bold, drawing attention to this part of the paragraph.

Color and Typography

Color and typography are crucial in CSS to bring personality and readability to your content.

Color:

Use the color and background-color properties to add life to your containers:

.info-box {
color: white;
background-color: darkslategray;
}

Typography:

Use font properties to make text aesthetically pleasing and readable:

.info-box {
font-family: 'Arial', sans-serif;
font-size: 16px;
line-height: 1.5;
}

Practical Activities: Styling Exercises

Info Box Creation: Create a <div> to serve as an information box. Style it with a background color, border, and padding. Experiment with different width values and margin to see how it affects the box's placement.

Text Highlighting: Use <span> elements within a paragraph to highlight certain text. Style these spans with background color and font weight. Try using different colors and font-style properties.

Conclusion

Styling <div> and <span> elements is a fundamental skill in CSS, setting the stage for more complex designs. As you practice these styling techniques, you'll develop a deeper understanding of how simple adjustments can dramatically transform the appearance of web content. Dive into these exercises with creativity and see how your containers evolve from plain HTML elements into visually engaging components of your web design. Happy styling!



Styling Semantic Containers

Elevating Web Design with Semantic HTML and CSS

Welcome to the world of styling semantic HTML containers! This section is all about using CSS to not only make your web content look good but also convey meaning and structure. Semantic containers like <header>, <footer>, <article>, and more, allow us to create web pages that are both aesthetically pleasing and meaningful. Let’s dive in and see how CSS brings out the best in these elements.

Styling the <header> Element

The <header> element typically contains the introductory content or navigational links of your webpage. It's crucial for the first impression.

HTML Structure:

<header>
<h1>Welcome to My Blog</h1>
<nav>
<!-- Navigation links here -->
</nav>
</header>

CSS Styling:

header {
background-color: navy;
color: white;
padding: 20px 10px;
text-align: center;
}

In this example, the <header> gets a navy background, white text, padding for spacing, and centered text. This creates a distinct area at the top of the page that is immediately recognizable as the header.

Styling the <footer> Element

A <footer> usually contains information about the author, copyright, and additional links. It’s often at the bottom of the page.

HTML Structure:

<footer>
<p>Copyright © 2024. All Rights Reserved.</p>
</footer>

CSS Styling:

footer {
background-color: darkslategray;
color: white;
padding: 15px;
text-align: center;
}

The footer is styled to stand out from the rest of the page, with a dark background, contrasting text color, and centered text.

Styling the <article> Element

The <article> element encapsulates a self-contained composition in a document, page, or site.

HTML Structure:

<article>
<h2>Styling with CSS</h2>
<p>CSS allows you to create visually engaging web pages...</p>
</article>

CSS Styling:

article {
border: 1px solid gray;
margin: 20px 0;
padding: 20px;
}

This gives each article a subtle border, margin for separation from other elements, and padding for internal spacing.

Consistency and Accessibility When styling semantic elements:

Consistency: Maintain consistent styling for similar elements. All <section> elements, for instance, should have a unified look.
Accessibility: Consider accessibility - ensure text is readable, links are distinguishable, and contrasts are adequate.

Conclusion

Styling semantic containers enhances the meaning and clarity of web content while also making it visually appealing. Remember, good web design is not just about looking great; it's about creating an intuitive and accessible experience for all users. As you style these elements, think about how each contributes to the overall narrative of your webpage. Let's continue to craft beautiful and meaningful web spaces!



CSS Box Positioning

Positioning: Placing Elements Exactly Where You Want Them

Welcome to the world of CSS positioning, a key tool in your web design toolkit! Here, we delve into how to precisely place and layout elements on your web page. Understanding CSS positioning is crucial for creating intricate layouts and ensuring elements appear exactly where you want them. Let’s unravel the secrets of CSS positioning together!

Positioning Concepts in CSS

CSS offers several positioning schemes that control how elements are placed on the page:

  • Static Positioning: This is the default positioning for any element. Elements are positioned according to the normal flow of the document.
  • Relative Positioning: Positions an element relative to its normal position.
  • Absolute Positioning: Removes the element from the normal document flow and positions it relative to its nearest positioned ancestor.
  • Fixed Positioning: Positions the element relative to the browser window, making it stay in place during scrolling.
  • Sticky Positioning: A hybrid of relative and fixed positioning. The element is treated as relatively positioned until it crosses a specified point, then it becomes fixed.

Implementing Different Positioning Types

Example 1: Relative Positioning

Consider a <div> that we want to shift slightly from its normal position.

HTML:

<div class="relative-box">Relative Box</div>

CSS:

.relative-box {
position: relative;
top: 10px;
left: 20px;
}

This CSS moves the <div> 10 pixels down and 20 pixels to the right from its normal position.

Example 2: Absolute Positioning

For absolute positioning, remember the element is positioned relative to its nearest positioned (not static) ancestor.

HTML:

<div class="container">
<div class="absolute-box">Absolute Box</div>
</div>

CSS:

.container {
position: relative; /* Needed for absolute positioning context */
}

.absolute-box {
position: absolute;
top: 5px;
right: 10px;
}

Here, .absolute-box is positioned absolutely within .container.

Example 3: Fixed Positioning

A fixed position element stays in place during scrolling.

HTML:

<div class="fixed-header">Fixed Header</div>

CSS:

.fixed-header {
position: fixed;
top: 0;
width: 100%;
background-color: #333;
color: white;
text-align: center;
}

This creates a header that stays at the top of the viewport regardless of scrolling.

Example 4: Sticky Positioning

Sticky positioning can be used for elements that you want to "stick" once you scroll past a certain point.

HTML:

<div class="sticky-nav">Sticky Navigation</div>

CSS:

.sticky-nav {
position: sticky;
top: 0;
background-color: yellow;
}

The navigation bar sticks to the top of the viewport when you scroll past it.

Conclusion

Mastering CSS positioning allows you to have complete control over where and how elements are displayed on your web pages. It's a powerful tool that, when used effectively, can significantly enhance the layout and user experience of your sites. Experiment with these positioning techniques and observe how they change the layout dynamics. Happy positioning!



Advanced Page Layout

Exploring Flexbox and Grid: The Power Duo of CSS Layouts

Welcome to the exciting world of Flexbox and Grid, the dynamic duo of CSS layout techniques! These powerful tools have revolutionized how we create complex, responsive layouts with ease. In this section, we'll explore the basics of Flexbox and Grid, understanding how they differ and how they can be used to create sophisticated web layouts.

Introduction to Flexbox

Flexbox, or the Flexible Box Module, is a one-dimensional layout method for arranging items in rows or columns within a container. It allows for flexible alignment and distribution of space among items in an interface.

Flexbox Basics:

Flex Container: The element that holds the flex items. It becomes a flex container when you apply display: flex; or display: inline-flex;.
Flex Items: The child elements within a flex container.

Example: Creating a Navigation Bar with Flexbox

HTML Structure:

<nav class="flex-nav">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Contact</a>
</nav>

CSS Styling:

.flex-nav {
display: flex;
justify-content: space-around;
align-items: center;
background-color: #333;
padding: 10px;
}

.flex-nav a {
color: white;
text-decoration: none;
}

In this example, the navigation links are evenly spaced and aligned centrally within the navigation bar.

Introduction to Grid

The CSS Grid Layout is a two-dimensional system, allowing you to handle both columns and rows. It’s ideal for creating complex layouts that require more control over both dimensions.

Grid Basics:

Grid Container: The element on which display: grid; is applied. It defines the grid.
Grid Items: The direct children of the grid container.

Example: Creating a Photo Gallery with Grid

HTML Structure:

<div class="grid-gallery">
<div class="item">1</div>
<div class="item">2</div>
<!-- More items here -->
</div>

CSS Styling:

.grid-gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
}

.item {
background-color: lightblue;
text-align: center;
padding: 20px;
}

This creates a three-column grid for the photo gallery, with even spacing between grid items.

Conclusion

Flexbox and Grid are incredibly powerful tools in your CSS arsenal, each with its unique strengths. Flexbox is ideal for one-dimensional layouts where you need to align items linearly, while Grid shines in two-dimensional layouts with more complex structuring needs. By mastering these techniques, you open up a world of possibilities for creating responsive, sophisticated web layouts. Dive in and start experimenting with these modern layout marvels! 



Responsive Design

Crafting Web Pages for Every Screen: Embracing Responsive Design

Welcome to the pivotal world of Responsive Web Design (RWD)! In today's multi-device environment, a website must look good and function well across all devices, from desktops to smartphones. This section will explore how to use CSS to make HTML containers responsive, ensuring they adapt to different screen sizes and orientations seamlessly.

The Essence of Responsive Design

Responsive design is about creating web pages that dynamically change their layout and appearance to fit the device and screen size. This approach uses fluid grids, flexible images, and media queries to adapt the layout and content.

Media Queries: The Heart of Responsiveness

Media queries are a key tool in responsive design. They apply CSS only when certain conditions are met, like specific screen sizes or orientations.

Basic Structure of a Media Query:

@media screen and (max-width: 600px) {
/* CSS rules for screens smaller than 600px */
}

Example: Responsive Container

HTML Structure:

<div class="responsive-container">Content here</div>

CSS Styling:

.responsive-container {
width: 80%;
margin: auto;
padding: 20px;
background-color: lightgray;
}

@media screen and (max-width: 600px) {
.responsive-container {
width: 100%;
padding: 10px;
}
}

In this example, the container takes up 80% of the width on larger screens but switches to 100% on screens smaller than 600px, adapting to the available space.

Creating a Responsive Layout

Let's use a combination of Flexbox/Grid and media queries to create a layout that adjusts based on screen size.

HTML Structure:

<div class="responsive-layout">
<header>Header</header>
<nav>Navigation</nav>
<main>Main Content</main>
<aside>Sidebar</aside>
<footer>Footer</footer>
</div>

CSS Styling:

.responsive-layout {
display: grid;
grid-template-columns: 1fr 3fr;
grid-template-areas:
"header header"
"nav main"
"aside main"
"footer footer";
}

@media screen and (max-width: 768px) {
.responsive-layout {
grid-template-columns: 1fr;
grid-template-areas:
"header"
"nav"
"main"
"aside"
"footer";
}
}

On larger screens, the layout consists of two columns with the header and footer spanning both columns. On screens smaller than 768px, the layout changes to a single column, with each section stacked vertically.

Conclusion

Responsive design is not just a trend; it's an essential skill in modern web development. By mastering media queries and understanding how to create fluid layouts with Flexbox and Grid, you'll be equipped to build websites that provide an optimal viewing experience on any device. Dive into the world of responsive design and make your web creations accessible and enjoyable for everyone, everywhere!



Best Practices

Crafting Elegant and Efficient CSS: The Path to Professional Web Design

Welcome to the art of writing efficient and organized CSS! As we explore the best practices in CSS styling, remember that the goal is not just to make web pages look good but to write CSS that is maintainable, scalable, and understandable. Let's dive into the strategies that will elevate your CSS skills to the next level!

CSS Efficiency and Organization

Efficient and well-organized CSS can significantly improve the performance and maintainability of your websites. Here are some key practices to adopt:

Use Shorthand Properties: Shorthand CSS properties allow you to set multiple values in a single property, reducing the size of your CSS and making it cleaner.

Example: Instead of writing margin-top, margin-right, margin-bottom, and margin-left separately, use the margin shorthand.

.container {
margin: 10px 15px 5px 20px; /* top, right, bottom, left */
}

Consistent Naming Conventions: Choose a naming convention (like BEM - Block Element Modifier) and stick with it throughout your project. This makes your CSS more readable and easier to understand.

Example:

.button { /* Block */ }
.button--large { /* Modifier */ }

Avoid Overly Specific Selectors: Overly specific selectors make your CSS less reusable and harder to override when needed. Aim for lower specificity where possible.

Bad Practice:

body home .content .sidebar ul li a { /* Too specific */ }

Good Practice:

.sidebar-link { /* More general, reusable */ }

Maintainability and Scalability

As your projects grow, maintainable and scalable CSS becomes crucial:

Modularize Your CSS: Break down your CSS into smaller, manageable modules. This could be per component or per page, depending on the project size.

Example: Have separate CSS files like header.css, footer.css, buttons.css, etc.

Commenting and Documentation: Regularly comment your CSS code and maintain documentation, especially for complex parts. This helps others (and your future self) understand your styling decisions.

Example:

/* Main navigation styling */
.nav {
...
}

Conclusion

Good CSS practices are not just about writing styles that work; they're about writing styles that last. Efficient, organized, and maintainable CSS is a hallmark of a professional web designer. As you apply these best practices, observe how they lead to smoother development experiences and more robust stylesheets. Embrace these practices and watch your CSS skills soar! 

Videos for Module 13: The CSS Box Model

There are no videos yet this term for this Module. Check back soon!

Activities for this Module

S13 - Magic Boxes CSS

Note: Sandbox assignments are designed to be formative activities that are somewhat open-ended. To get the most value, spend some time playing around as you code.

In this sandbox, I'm going to walk you through a series of changes to a starting template that will demonstrate a concept called CSS Positioning.  CSS Positioning allows you to move different objects and HTML containers around the screen, achieving some really interesting effects.  I'll show you some of the basic concepts, and then I'll challenge you to play around and combine the different concepts to see what kind of effects you can come up with on your own.

Start out with a new, default Liveweave document.

Paste the following code into the Liveweave HTML pane:

<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->
<div class='box redbox'>Red</div><div class='box greenbox'>Green</div><div class='box bluebox'>Blue</div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<!-- End your code here -->
</body>
</html>

Copy and paste the following code into the CSS pane:

.box {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    line-height: 100px;
    text-align: center;
    border-radius: 10px;
    font-family: Arial, Helvetica, sans-serif;
    color: white;
    margin: 0px;
}

.redbox {
    background-color: red;
}

.greenbox {
    background-color: green;    
}

.bluebox {
    background-color: blue;
}

You should now see red, green and blue boxes in the results pane. They should be stacked vertically in the order they appear on the page.  This is because, as you have learned, the div tag by default is set to "display: block", which means that the following are true: 

  • Starts on a New Line: A block-level element always starts on a new line, taking up the full width available (its parent element’s width) by default.
  • Width and Height: You can set the width and height of a block-level element using CSS properties.\
  • Margin and Padding: Block-level elements respect margin and padding settings, allowing you to control the spacing around and inside the element.
  • Stacking: Block-level elements stack vertically, one after the other.

Common block-level elements include <div>, <p>, <h1>, <section>, and <article>. You can also change an inline element to behave like a block-level element using display: block.

We can also affect the way a block-level element displays by using the "position" CSS property. Let's try a few things.

in the .greenbox CSS Class, add the following:

position: relative;

So far, you won't see anything different. Add one more thing:

left: 100px;

The Green Box should now be shifted to the right so that its left side is just to the right of the other boxes. Specifically, the code above says that the left side of the box should be 100 pixels to the right of its original position. The "position: relative" property says that the box should display relative to its position on the page, but this also means that it takes up space on the page at its original location. That's why the blue box doesn't move up into that place.

Try adding the following:

top: -100px;

Now the Green box should be up next to the red box.  The "-100px" value tells the Green box to display 100 pixels up from its original location (negative numbers are further up, because the top left of the page is 0 pixels across and 0 pixels down)

Reset the .greenbox class to the following:

.greenbox {
    background-color: green;
}

Let's try a different positioning value. Add the following to the .greenbox class:

position: absolute;

Notice that you can no longer see the blue box.  It didn't disappear. It's actually "hiding" behind the green box, because when you changed the position to "absolute", you took the green box out of the document flow.  What this means is that while the element still displays, it doesn't affect the positioning of the other elements on the page.  As far as their position is concerned, the green box doesn't exist.

Add the following to the .greenbox class:

top: 100px;
left: 100px;

Now you should be able to see all three boxes, but they won't be perfectly aligned. Even though the boxes are 100 pixels tall and wide, the green box isn't lined up, but rather it is shifted about 10 pixels up, and 10 pixels to the left.

Why?

The reason for this is because in "absolute" positioning, the element's position is measured from the 0,0 position on the page. Unlike relative, it ignores other aspects of the page, including the default margins of the page. Notice that the red and blue boxes aren't all the way at the top or left of the page -- By default, the page (or the body tag) has margins that all the elements of the page follow, unless they have a few specific settings in the "position" property.

Let's add the following to the very top of the CSS pane:

body {
    margin: 0px;
}

This should result in the red and blue boxes shifting to the very edges of the page. However, if you look very closely, you will see that the green box is still a little off. Why? Because each box is 100 pixels wide, PLUS they have a 1 pixel border on each side.  This means that they are actually 102 pixels wide and 102 pixels tall including the border. Change the top and left properties of the green box to 102px to get everything to line up.

Take a second and try scrolling up and down in the results pane.  If you can't scroll, then add a few more of the following line to the HTML to mage sure that the page length is bigger than the size of the pane:

<p>&nbsp;</p>

Change the position of the green box to the following:

position: fixed;

Now try scrolling.  The green box should stay put while the other elements of the page scroll up and down normally. Both "fixed" and "absolute" take the element out of the page flow and put it in the same place.  However, absolute is places from the page 0,0 corner and fixed is placed from the 0,0 corner of the window, so that it doesn't scroll when the page does.

Try some different combinations to see what you can do with different position settings. Post a screenshot of what you come up with. 

For an extra challenge, see if you can create the following layout:

Three boxes, diagonally placed and overlapping. From top-left to bottom-right: blue, green, red.

Post the following:

  1. You can post screenshots of your code or the results of your code when it is run.
  2. Something you learned from this.
  3. Something you struggled with or found difficult.

Please return to this discussion throughout the module, and see if you can either learn from your classmates' work or help them develop their understanding. While I don't count posts, I expect each of you to post your Sandbox Challenge and reply to about 1 classmate per module.

A13 - CSS Zen Garden

The Challenge

CSSZenGarden.com has existed for a very long time, and was an early example of what could be done using CSS in powerful ways.  For this assignment, I want you to spend some time looking at some of the example designs, and trying to uncover some of the techniques they use to produce them.  Don't worry - I don't expect your designs to be at this level, but I do want you to try to stretch what you are able to do with CSS. You will download the html file, but you will start from scratch with your own CSS.  Pay attention to the classes and ID attributes in the HTML file as a way of targeting the parts of the HTML file for styling.  Lastly, I'd like you to try to think of a theme that uses images and colors well to communicate your design.

Resources

csszengarden.com

If you download the two files below, and put them both in your same folder, then changes you make to the CSS file will impact the HTML file.  Don't forget to upload the files after you change them for the changes to take effect.

Download the files for A13

Grading / Success Criteria

To earn credit for this assignment, it must:

  • Only edit CSS to change the file.
  • Start with your own blank CSS file.
  • Your design should use at least one image, and should coordinate colors in a theme.