Code
index.html
<!DOCTYPE html> <html> <head> tab<title> </title> </head> <body> </body> </html>
Link to a Stylesheet
<link rel="stylesheet" type="text/css" href="main.css"/> About link: The link element uses three attributes: -rel: Specifies the relationship between the current file and the file being linked to: in this case, the rel attribute is "stylesheet". -type: Specifies the type of file linked to. -href: Provides the URL of the file being linked to. Like the HTML image element, link is self-closing. It does not need a closing tag. In the example above, main.css is an external style sheet. Using external stylesheets is one of the most popular ways to write CSS. Inline CSS is another method. Inside the head element of index.html, insert a link element that connects index.html and main.css.
CSS id Selectors
A previous exercise introduced CSS class selectors to style HTML elements of specific classes. What if a webpage design calls for an individual page element to be styled uniquely, but all other elements of that kind to be styled a different way? For example, to style one anchor element differently than all the others on a webpage, you could use the HTML id attribute: <a id="learn-code" href="https://www.codecademy.com">Click here to learn to code!</a> Then in the CSS file, you would create a rule for the id selector, using a # symbol: #learn-code { color: #2e69a3; } About using id: An id attribute can only be used once because the id is unique to the element it is assigned to. Ids have greater specificity than classes. If an HTML element is using both id and class attributes, the CSS rule for the id will take precedence over that of the class. Below we will use an id selector to style a single HTML element differently than others of that kind on the webpage.
Background: Color
A wide variety of different background styles are used across many modern websites today. Some sites use large images in their layout, while others use creative color gradients as their background. The background-image property you learned about earlier allows you to do more than simply set the background image of an element. It also lets you use color gradients in your web page. Gradients are planned to be a part of the newest revision of CSS, CSS3. Due to the many browsers available, there is no standard way of defining a gradient using CSS (different browsers require different syntax). In this exercise, we'll look at one value supported on a couple of major browsers. The background-image property can be set to the following value: -webkit-linear-gradient() - this value accepts two arguments: the two colors the linear gradient will transition to and from. The colors are usually specified as hex color codes. div.header { height: 400px; width: 400px; background-image: -webkit-linear-gradient(#666CCC, #BC1324); } In a later course, you'll learn more about the -webkit-linear-gradient syntax, as well as other similar CSS values. For now, it's important to understand how to create a linear gradient using the value in the example above.
Display
All HTML elements can be classified as one of the following: inline elements or block-level elements. 1. Inline elements - elements that display inline with text, without disrupting the flow of the text (like links). 2. Block-level elements - elements that use an entire line of space in a web page and disrupt the natural flow of text. Most of the common HTML elements are block-level elements (headings, paragraphs, divs, and more). In CSS, you can change the default behavior of elements with the display property. Why is this useful? Modifying the display property of an element can help achieve a desired layout for a web page. The display property can take on one of four values: 1. inline - causes block-level elements (like a div) to behave like an inline element (like a link). 2. block - causes inline elements (like a link) to behave like a block element (like a div). 3. inline-block - causes block-level elements to behave like an inline element, but retain the features of a block-level element. 4. none - removes an element from view. The rest of the web page will act as if the element does not exist. It's common to use the display property to create a navigation bar from list items, like so: <ul> <li>Home</li> <li>Products</li> <li>Settings</li> <li>Inbox</li> </ul> li { display: inline; } In the example above, the block-level list items will now behave as inline elements. The result will be list items appearing on the same line, like a navigation bar.
Resetting Defaults
All major web browsers have a default stylesheet they use in the absence of an external stylesheet. These default stylesheets are known as user agent stylesheets. In this case, the term "user agent" is a technical term for the browser. User agent stylesheets often have default CSS rules that set default values for padding and margin. This affects how the browser displays HTML elements, which can make it difficult for a developer to design or style a web page. Many developers choose to reset these default values so that they can truly work with a clean slate. Here is an example: * { margin: 0; padding: 0; } The code in the example above resets the default margin and padding values of all HTML elements. It is often the first CSS rule in an external stylesheet. Note that both properties are both set to 0. When these properties are set to 0, they do not require a unit of measurement.
Color
Along the way, we styled a different properties of HTML elements, but the details of each property weren't explained. For example, we changed the colors of headings and paragraphs, but we didn't explore the full power and versatility of color. Professional websites often use various aspects of color in order to create a visually appealing user experience (UX). In this lesson, you'll learn how to use CSS to style web pages with color.
<style> within index.html
Although CSS is a different language than HTML, it's possible to write CSS code directly within an HTML file. This is possible because of the <style> element. The <style> element allows you to write CSS code between its opening and closing tags. To use the <style> element, it must be placed inside of the head. Here is an example: <head> <style> </style> </head> Once <style> is placed in the web page's head, we can begin writing CSS code. Here is another example: <head> <style> h2 { font-family: Arial; } </style> </head>
RGB Colors
Although named colors provide 147 different options, this is a small amount when you consider the flexibility of CSS. To take advantage of the full spectrum of colors that CSS supports, you have the option of using RGB colors. RGB (Red, Green, Blue) colors offer the option of 16,777,216 possible colors. How is that possible? RGB colors work by mixing together different amounts of red (R), green (G), and blue (B). Each color (R, G, or B) can take on 1 of a possible 256 values (between 0 and 255). This results in 16,777,216 possible colors. To use RGB colors, you can use the rgb() value when styling a color. Here is an example: h1 { color: rgb(123, 20, 233); background-color: rgb(99, 21, 127); } In the example above, the value of color is set to rgb(). The three numbers in the parentheses represent the values for R, G, and B, in that order. Note that you can use rgb() for background colors as well. How can you tell what color the RGB values in the example above will result in? Are you expected to memorize 16,777,216 possibilities? Thankfully, no! There are many resources on the Internet known as "color pickers" that allow you to view the result of different RGB values before you decide to use a certain color. If you're ever in need of a color picker resource, a quick Google search will yield the results you are looking for.
Width: Minimum & Maximum
Although relative measurements provide consistent layouts across devices of different screen sizes, elements on a website can lose their integrity when they become too small or large. You can limit how wide an element becomes with the following properties: min-width — ensures a minimum width for an element. max-width — ensures a maximum width for an element. p { min-width: 300px; max-width: 600px; } In the example above, when the browser is resized, the width of paragraph elements will not fall below 300 pixels, nor will their width exceed 600 pixels. When a browser window is narrowed or widened, text can become either very compressed or very spread out, making it difficult to read. These two properties ensure that content is legible by limiting the minimum and maximum widths. Note: The unit of pixels is used to ensure hard limits on the dimensions of the element(s).
Width & Height
An element's box has two dimensions: a height and a width. In HTML, all boxes have default dimensions. These default dimensions are automatically set to hold the raw contents of the box. To modify the default dimensions an element's box in CSS, you can use the width and height properties. These two properties can be specified with the following units of measurement: 1. Pixels - You learned about pixels when you learned about fonts. This unit lets you set the exact size of an element's box. 2. Ems - This unit sets the dimensions of the box relative to the size of the text within the box. 3. Percentages - This unit sets the dimensions of the box relative to the size of the box that it is encased in. For example, consider an element (a box) of class blue set to a height of 200 pixels and a width of 200 pixels. Inside of blue, consider another box of class red, set to a height of 37% and a width of 45%. The resulting dimensions of the red box would be a height of 74 pixels and a width of 90 pixels. Developers often use ems or percentages to set box dimensions. Because many web pages are now accessed on mobile devices and other displays of differing sizes, ems and percentages allow boxes to scale depending on the size of a user's display.
Dots Per Inch (DPI)
Another media feature we can target is screen resolution. Many times we will want to supply higher quality media (images, video, etc.) only to users with screens that can support high resolution media. Targeting screen resolution also helps users avoid downloading high resolution (large file size) images that their screen may not be able to properly display. To target by resolution, we can use the min-resolution and max-resolution media features. These media features accept a resolution value in either dots per inch (dpi) or dots per centimeter (dpc). Learn more about resolution measurements here. @media only screen and (min-resolution: 300dpi) { /* CSS for high resolution screens */ } The media query in the example above targets high resolution screens by making sure the screen resolution is at least 300 dots per inch. If the screen resolution query is met, then we can use CSS to display high resolution images and other media.
Position: Absolute
Another way of modifying the position of an element is by setting its position to absolute. When an element's position is set to absolute all other elements on the page will ignore the element and act like it is not present on the page. Here is an example: .box-bottom { background-color: DeepSkyBlue; position: absolute; top: 20px; left: 50px; } In the example above, the .box-bottom div will be moved down and right from the top left corner of the view. If offset properties weren't specified, the top box would be entirely covered by the bottom box. Take a look at the gif below: The bottom box in this image (colored blue) is displaced from the top left corner of its container. It is 20 pixels lower and 50 pixels to the right of the top box. In the next exercise we will compare the scrolling of absolute elements with fixed elements.
<html> tags
Anything between <html> and </html> will be considered HTML code. Without these tags, it's possible that browsers could incorrectly interpret your HTML code and present HTML content in unexpected ways.
Width x Height
As with any other element, the dimensions of an image can be set with the height and width properties. Here is an example: <img src="#" alt="A red leaf" class="leaf" /> img.leaf { width: 350px; height: 200px; } Specifying the dimensions of an image helps the browser determine how much space should be reserved for the image. Note: Images should be saved at the dimensions they will be displayed in on the web page. Using dimensions for an image that exceed the original dimensions will distort the image.
Add a Video
Awesome! The photo makes the webpage much cooler. What's cooler than a photo? A video! The HTML video element can add video to a webpage. <video width="320" height="240" controls> <source src="video-url.mp4" type="video/mp4"> </video> The video element uses a number of attributes. Let's take a look at them: width and height: Set the size of the screen that displays the video. controls: Adds play, pause and volume control. source src: Sets the URL of the video to play. type: Specifies different video formats.
Scaling Background Images
Background images of HTML elements can also be scaled responsively using CSS properties. body { background-image: url('#'); background-repeat: no-repeat; background-position: center; background-size: cover; } In the example above, the first CSS declaration sets the background image (# is a placeholder for an image URL in this example). The second declaration instructs the CSS compiler to not repeat the image (by default, images will repeat). The third declaration centers the image within the element. The final declaration, however, is the focus of the example above. It's what scales the background image. The image will cover the entire background of the element, all while keeping the image in proportion. If the dimensions of the image exceed the dimensions of the container then only a portion of the image will display.
Width: Minimum and Maximum
Because a web page can be viewed through displays of differing screen size, the content on the web page can suffer from those changes in size. To avoid this problem, CSS offers two properties that can limit how narrow or how wide an element's box can be sized to. min-width - this property ensures a minimum width for an element's box. max-width - this property ensures a maximum width for an element's box. Here is an example: p { min-width: 300px; max-width: 600px; } In the example above, the width of all paragraphs will not shrink below 300 pixels, nor will the width exceed 600 pixels. Content, like text, can become difficult to read when a browser window is narrowed or expanded. These two properties ensure that content is legible by limiting the minimum and maximum widths of an element.
Connecting To Bootstrap
Before Bootstrap can work for us, we need to link to it. In earlier lessons, we linked only to main.css. Now, in addition to main.css, we will link to a URL that hosts Bootstrap. The HTML link element makes Bootstrap available to us. Remember that the link element is typically contained within HTML head tags. <head> ... <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/> ... </head> Above, the href attribute is set to the URL https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css. Let's explore what Bootstrap can do for us. Instructions 1. Notice the "Skillfair" webpage to the right and locate the diagonal arrows in the top right corner of the web browser (near https://localhost:8000/). Click the arrows to toggle the web browser between narrow and full-width views, and observe the following: Navbar items do not change position as you toggle the webpage width. The "Homemade Goods" text appears on the far left side of the webpage. Photographs increase in size when the web browser is toggled to full-width. Social media icons at the bottom of the webpage appear disorganized. Click Run after you have observed these points. 2. Now we will connect to Bootstrap and see changes to the webpage layout. In index.html, locate the head element. Inside head, create a link element to link to Bootstrap: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/> Click Run. Toggle the web browser's width again to notice the following changes: Navbar items change position based on the webpage's width. The "Homemade Goods" text is now centered. "Kitchen", "woodwork", "antique" and "gifts" photographs are arranged two per row when the webpage is full-width. Social media icons appear organized and change position at full and narrow widths. Bootstrap's grid is responsible for this screen-width responsiveness. Click Next to learn more!
Foreground vs Background
Before discussing the specifics of color, it's important to make two distinctions about color. Color can affect the following design aspects: 1. The foreground color 2. The background color Foreground color is the color that an element appears in. For example, when a heading is styled to appear green, the foreground color of the heading has been styled. Conversely, when a heading is styled so that its background appears yellow, the background color of the heading has been styled In CSS, these two design aspects can be styled with the following two properties: 1. color - this property styles an element's foreground color. 2. background-color - this property styles an element's background color. Here is an example: h1 { color: Red; background-color: Blue; } In the example above, the text of the heading will appear in red, and the background of the heading will appear blue.
Create A Table
Before displaying data, you must first create the table that will contain the data by using the <table> element. <table> </table> The <table> element will contain all of the tabular data you plan on displaying.
Anatomy of CSS Rule
Before we start writing our own CSS, let's take a look at how CSS code works. The diagram to the right shows the anatomy of a CSS rule: rule: a list of CSS instructions for how to style a specific HTML element or group of HTML elements. selector: specifies exactly which HTML elements to style. Here h1 is the selector. properties and values: located inside the { } brackets, properties and values specify what aspect of the selector to style. In the diagram's example, the color property is set to red, which will display all h1 elements in red.
The Content Inside
Box dimensions and borders are just the beginning of the vast number of box properties you can modify in CSS. In this lesson, you'll learn how to modify the spacing around the content inside of the box. This concept is critical in understanding how to customize the way content is displayed to users.
Multiple Selectors: CSS
CSS does not limit you to selectors that target a single element or class. In a previous exercise, you learned how to use a multiple element selector to style multiple elements at once. Previous: h1, p { font-family: Garamond, serif; } The same syntax can be used to style multiple classes at once. Here is an example: .first, .last { font-size: 20px; } Using a multiple class selector is an efficient way of styling multiple HTML elements.
Media Queries
CSS uses media queries to adapt a website's content to different screen sizes. With media queries, CSS can detect the size of the current screen and apply different CSS styles depending on the width of the screen. @media only screen and (max-width: 480px) { body { font-size: 12px; } } The example above demonstrates how a media query is applied. The media query defines a rule for screens smaller than 480 pixels (approximately the width of many smartphones in landscape orientation). Let's break this example down into its parts: 1. @media — This keyword begins a media query rule and instructs the CSS compiler on how to parse the rest of the rule. 2. only screen — Indicates what types of devices should use this rule. In early attempts to target different devices, CSS incorporated different media types (screen, print, handheld). The rationale was that by knowing the media type, the proper CSS rules could be applied. However, "handheld" and "screen" devices began to occupy a much wider range of sizes and having only one CSS rule per media device was not sufficient. screen is the media type always used for displaying content, no matter the type of device. The only keyword is added to indicate that this rule only applies to one media type (screen). 3. and (max-width : 480px) — This part of the rule is called a media feature, and instructs the CSS compiler to apply the CSS styles to devices with a width of 480 pixels or smaller. Media features are the conditions that must be met in order to render the CSS within a media query. 4. CSS rules are nested inside of the media query's curly braces. The rules will be applied when the media query is met. In the example above, the text in the body element is set to a font-size of 12px when the user's screen is less than 480px.
CSS
CSS, or Cascading Style Sheets, is a language that web developers use to style the HTML content on a web page. If you're interested in modifying colors, font types, font sizes, shadows, images, element positioning, and more, CSS is the tool for the job!
Font Size 1
Changing the typeface isn't the only way to customize text. Often times, different sections of a web page and are highlighted by modifying the font size. To change the size of text on your web page, you can use the font-size property. Here is an example: p { font-size: 18px; } In the example above, the font-size of all paragraphs was set to 18px. What exactly does px mean? Measurements require units in order for them to be useful (for example kilograms for weight, or miles for distance). Font size also requires a unit of measurement. In the next exercise, we'll explore in detail the units of measurement available for font size.
The Div
Classes and IDs are useful for labeling elements, but a disorganized, overuse of classes and IDs can result in an HTML file that is difficult to read. We need a way of organizing the contents of the HTML file. This will help: 1. Keep HTML code easy to read. 2. Group elements that belong together. HTML offers an element that is the backbone of code organization: the div, represented by <div> in HTML. You can think of the div as a box, or container, that groups elements that belong together. For example, a <div> can be used to group together all of the elements that make up the navigation for a web page, or any other section of a page. Here is an example: <div> <h1>Alice In Wonderland</h1> <p> ... </p> </div> In the example above, a heading for "Alice In Wonderland" and a brief paragraph description of the book are contained within a single <div>. If more books were to appear on the page, additional divs could be used to organize them. This would keep the code easier to read, maintain, and style.
Why Fonts Matter
Colors are an important aspect of the user experience (UX), but an overview of UX is not complete without a focus on fonts. It's very likely that a lot of the important information a user will see on a web page will be in the form of text. Styling text to make web page content accessible and visually engaging creates a great experience for users. In this lesson, we'll learn all about fonts and how to style their appearance with CSS.
Code
Computer code is a set of statements and each statement directs the computer to perform a single step or instructions
Spanning Rows
Data can also span multiple rows using the rowspan attribute. The rowspan attribute is used for data that spans multiple rows (perhaps an event goes on for multiple hours on a certain day). It accepts an integer (greater than or equal to 1) to denote the number of rows it spans across. <table> <tr> <!-- Row 1 --> <th></th> <th>Saturday</th> <th>Sunday</th> </tr> <tr> <!-- Row 2 --> <th>Morning</th> <td rowspan="2">Work</td> <td rowspan="3">Relax</td> </tr> <tr> <!-- Row 3 --> <th>Afternoon</th> </tr> <tr> <!-- Row 4 --> <th>Evening</th> <td>Dinner</td> </tr> </table> In the example above, there are four rows: The first row contains an empty cell and the two column headings. The second row contains the Morning row heading, along with Work, which spans two rows under the Saturday column. The "Relax" entry spans three rows under the Sunday column. The third row only contains the Afternoon row heading. The fourth row only contains the Dinner entry, since "Relax" spans into the cell next to it.
Keep It Inline
Display types can be overwritten in CSS by using the display property. For example, we can make list items appear on the same line by setting display to inline: li { display: inline; } Note: Below, we will encounter an HTML nav element. Navs are used to organize site navigation menus on a webpage.
Fallback Fonts
Earlier, you learned that users must have the fonts specified in the stylesheet installed on their computer in order for their browser to display that font. What happens when a font is not installed on a user's computer? Most computers have a small set of typefaces pre-installed. This small set includes serif fonts and sans-serif fonts, like Times New Roman and Arial, respectively. When the stylesheet specifies a font not installed on a user's computer, the pre-installed fonts can be used as fallback fonts for users. To use fallback fonts, the following syntax is required: h1 { font-family: Garamond, Times, serif; } The CSS rule above says: "Use the Garamond font for all <h1> elements on the web page. If that font is not available, use the Times font. If both of those fonts are not available, use any serif font pre-installed on the user's computer." The fonts specified after Garamond are the fallback fonts. Fallback fonts help ensure a consistent experience for the diverse audience of users that visit a site.
Visability
Elements can be hidden from view with the visibility property. The visibility property can be set to one of the following values: hidden - hides an element. visible - displays an element. Here is an example: <ul> <li>Explore</li> <li>Connect</li> <li class="future">Donate</li> <ul> .future { visibility: hidden; } In the example above, the list item with a class of future will be hidden from view in the browser. Keep in mind, however, that users can still view the contents of the list item (e.g., Donate) by viewing the source code in their browser. Furthermore, the web page will only hide the contents of the element. It will still leave an empty space where the element is intended to display. Note: What's the difference between display: none and visibility: hidden? An element with display: none will be completely removed from the web page. An element with visibility: hidden, however, will not be visible on the web page, but the space reserved for it will.
Border Radius
Ever since we revealed the borders of boxes, you may have noticed that the borders highlight the true shape of an element's box: square. Thanks to CSS, a border doesn't have to be square. The corners of an element's border box can be modified with the border-radius property. Here is an example: div.container { border: 3px solid rgb(22, 77, 100); border-radius: 5px; } The code in the example above will set all four corners of the border to a radius of 5 pixels (i.e. the same curvature that a circle with radius 5 pixels would have). You can create a border that is a perfect circle by setting the radius equal to the height of the box, or to 100%. Here is the example to this: div.container { height: 60px; width: 60px; border: 3px solid rgb(22, 77, 100); border-radius: 100%; } The code in the example above creates a div that is a perfect circle.
style.css
Fortunately, the following solution will help you avoid creating large HTML files that mix in CSS code: a CSS file! HTML files are meant to contain only HTML code. Similarly, CSS files are meant to contain only CSS code. You can create a CSS file by using the .css file name extension, like so: style.css With a CSS file, you can write all the CSS code needed to style a page without having to sacrifice the readability and maintainability of your HTML file.
Box Model: Border-Box
Fortunately, we can reset the entire box model and specify a new one: border-box. * { box-sizing: border-box; } The code in the example above resets the box model to border-box for all HTML elements. This new box model avoids the dimensional issues that exist in the former box model you learned about. In this box model, the height and width of the box will remain fixed. The border thickness and padding will be included inside of the box, which means the overall dimensions of the box do not change. Here is an example: <h1>Hello World</h1> * { box-sizing: border-box; } h1 { border: 1px solid black; height: 200px; width: 300px; padding: 10px; } In the example above, the height of the box would remain at 200 pixels and the width would remain at 300 pixels. The border thickness and padding would remain entirely inside of the box. The width property is the same as the actual rendered width of the element. The content area is automatically sized based on the remaining width, after border and padding has been subtracted
Comments in HTML
HTML files also allow you to add comments to your code. Comments begin with <!-- and end with -->. Any characters in between will be treated as a comment. Here is an example: <!-- This is a comment that the browser will not display. --> Including comments in your code is helpful for many reasons: 1. They help you (and others) understand your code if you decide to come back and review it at a much later date. 2. They allow you to experiment with new code, without having to delete old code. Here is another example: <!-- Favorite Films Section --> <p>The following is a list of my favorite films:</p> In the example above, the comment is used to denote that the following text makes up a particular section of the page. Here is another example: <!-- <a href="#" target="_blank>Codecademy</a> --> In the example above, a valid HTML element (an anchor element) has been "commented out." This practice is useful when you want to experiment with new code without having to delete old code.
Ordered Lists
HTML provides the ordered list when you need the extra ordering that unordered lists don't provide. Ordered lists are like unordered lists, except that each list item is numbered. You can create the ordered list with the <ol> element and then add individual list items to the list using <li> elements. Here is an example: <ol> <li>Preheat the oven to 350 degrees.</li> <li>Mix whole wheat flour, baking soda, and salt.</li> <li>Cream the butter, sugar in separate bowl.</li> <li>Add eggs and vanilla extract to bowl.</li> </ol>
Target Attribute
Have you ever clicked on a link and observed the resulting web page open in a new browser window? If so, you can thank the anchor element's target attribute. The target attribute specifies that a link should open in a new window. Why is it beneficial to open links in a new window? It's possible that one or more links on your web page link to an entirely different website. In that case, you may want users to read the linked website, but hope that they return to your web page. This is exactly when the target attribute is useful! For a link to open in a new window, the target attribute requires a value of _blank. The target attribute can be added directly to the opening tag of the anchor element, just like the href attribute. Here is an example: <a href="https://en.wikipedia.org/wiki/Brown_bear" target="_blank">The Brown Bear </a> In the example above, the link would read The Brown Bear and open up the relevant Wikipedia page in a new window.
Classes: HTML
IDs are great for labeling unique elements, but IDs have a limitation. Because unique IDs should not be used across multiple HTML elements, they are insufficient for quickly styling elements that should all share a specific style. CSS offers a solution to this limitation. For multiple elements that should share the same styling, classes can be used to label them. To label an element with a class, we can use the class attribute on an HTML element. Here is an example: <h1 class="science">Scientist Discovers Important Cure</h1> <h1 class="science">New Study Reveals The Importance of Sleep</h1> In the example above, there are two headings with a class of science. Why? HTML elements are often labeled with class names that reflect the content they represent on the web page. In the example above, perhaps a news company decided that all news headlines about science should be labeled with a class of science. Later, in the stylesheet, all science headlines can be quickly styled to have the same styling.
Comma Separated List
If only one of multiple media features in a media query must be met, media features can be separated in a comma separated list. For example, if we needed to apply a style when only one of the below is true: The screen is more than 480 pixels wide The screen is in landscape mode We could write: @media only screen and (min-width: 480px), (orientation: landscape) { /* CSS ruleset */ } In the example above, we used a comma (,) to separate multiple rules. The example above requires only one of the media features to be true for its CSS to apply. Note that the second media feature is orientation. The orientation media feature detects if the page has more width than height. If a page is wider, it's considered landscape, and if a page is taller, it's considered portrait.
Line Breaks
If you are interested in modifying the spacing in the browser, you can use HTML's line break element: <br />. The line break element is one self-closing tag. You can use it anywhere within your HTML code and a line break will be shown in the browser. Here is an example: Shall I compare thee to a summer's day?<br />Thou art more lovely and more temperate The code in the example above will result in an output that looks like the following: Shall I compare thee to a summer's day? Thou art more lovely and more temperate
Paragraphs
If you want to add content in paragraph format, you can add a paragraph using the paragraph element <p>. Here is an example: <p>The Nile River is the longest river in the world, measuring over 6,850 kilometers long (approximately 4,260 miles). It flows through eleven countries, including Tanzania, Uganda, Rwanda, Burundi, Congo-Kinshasa, Kenya, Ethiopia, Eritrea, South Sudan, Sudan, and Egypt.</p>
Margin 4
If you want to be even more specific about the amount of margin on each side of a box, you can use the following properties: margin-top margin-right margin-bottom margin-left Each property affects the margin on only one side of the box, giving you more flexibility in customization. Here is an example: p { border: 3px solid #2D3FA3; margin-right: 15px; } In the example above, only the right side of the paragraph's box will have a margin of 15 pixels. Because the margin property directly modifies the space outside of a box, it's very common to see margin values used for only specific sides of boxes. As you learn more about web development, you'll likely come across many different ways of positioning elements with the margin property.
Padding 4
If you want to be even more specific about the amount of padding on each side of a box's content, you can use the following properties: padding-top padding-right padding-bottom padding-left Each property affects the padding on only one side of the box's content, giving you more flexibility in customization. Here is an example: p { border: 3px solid #2D3FA3; padding-bottom: 10px; } In the example above, only the bottom side of the paragraph's content will have a padding of 10 pixels.
Border Width 3
If you'd like to be even more specific about the width of different sides of the border, you can use the following properties: border-top-width border-right-width border-bottom-width border-left-width Each property affects the width of only one side of the border, giving you more flexibility in customization. Here is an example: p { border-style: solid; border-left-width: 4px; } In the example above, only the left side of the border will be set to a width of 4 pixels.
Font Family
If you've ever used a formatted word processor, chances are that you probably also used a feature that allowed you change the "type of font" you were typing in. The phrase "type of font" refers to the technical term typeface, or font family. To change the typeface of text on your web page, you can use the font-family property. Here is an example: h1 { font-family: Garamond; } In the example above, the font family for all main heading elements has been set to Garamond. When setting typefaces on a web page, keep the following points in mind: 1. The font specified in a stylesheet must be installed on a user's computer in order for that font to display when a user visit the web page. We'll learn how to work around this issue in a later exercise. 2. You've probably noticed that we haven't been specifying a typeface in previous exercises of this course. How exactly does the browser know what typeface to use when displaying the web page? The default typeface for all HTML elements is Times New Roman. You may be familiar with this typeface if you have ever used a formatted word processor. 3. It's a good practice to limit the number of typefaces used on a web page to 2 or 3. 4. When the name of a typeface consists of more than one word, it must be enclosed in double quotes (otherwise it will not be recognized), like so: h1 { font-family: "Courier New"; }
Background: Images
Images can also be added to the backgrounds of HTML elements with the background-image property. body { background-image: url("https://www.example.com/leaf.jpg"); } The background-image can be set to a value of url(). 1. url() - contains the URL of the image, enclosed in double quotes. In the example above, the background of the body will be set to the image specified in double quotes. This technique can be used on nearly any HTML element.
Centering Images
Images can also be centered, but first, their default behavior must be changed. By default, images are inline elements. For images to center properly, they must behave as block-level elements. img.leaf { width: 300px; height: 200px; display: block; } In the example above, the image's display property has been set to block. Now the image can be aligned as a block-level element. img.leaf { width: 300px; height: 200px; display: block; margin: 0px auto; } In the example above, the image is aligned using the margin property. The top and bottom margins of the image's box are set to 0 margin. The left and right margins are set to auto, which automatically sets the exact amount of margin needed on the left and right sides in order to center the image. Note: To align images to the left or right side of a page, you can use the float property you learned about earlier.
A Background Image
In CSS, the background-image property sets a background image of your choice for a given selector, as seen below. .hero { background-image: url("https://s3.amazonaws.com/codecademy-content/projects/make-a-website/lesson-2/bg.jpg"); } The CSS rule above assigns the image hosted at https://s3.amazonaws.com/codecademy-content/projects/make-a-website/lesson-2/bg.jpg to elements that have a class attribute set to hero. To control the size of the chosen background image, use the property background-size as seen below: .hero { background-image: url("https://s3.amazonaws.com/codecademy-content/projects/make-a-website/lesson-2/bg.jpg"); background-size: cover; } Here, we have specified that we want the image to completely cover elements with the .hero class.
Headings
In HTML there are six (6) different headings or heading elements, each has a different size to them. Headings can be used for a variety of purposes, like titling sections, articles, or other forms of content. The following is the list of heading elements available in HTML. They are ordered from largest to smallest in size. <h1> - used for main headings, all other smaller headings are used for subheadings. <h2> <h3> <h4> <h5> <h6> Here is an example: <h1>BREAKING NEWS</h1>
Unordered Lists
In HTML, you can use the unordered list for text you decide to format in bullet points. An unordered list outlines individual list items with a bullet point. You've probably used an unordered list when writing down a grocery list or school supplies list. To create a unordered list using HTML, you can use the <ul> element. The <ul> element, however, cannot hold raw text and cannot automatically format raw text with bullet points. Individual list items must be added to the unordered list using the <li> element. Here is an example: <ul> <li>Limes</li> <li>Tortillas</li> <li>Chicken</li> </ul> In the example above, the list was created using the <ul> element and all individual list items were added using <li> elements.
Table Rows
In many programs that use tables, the table is already predefined for you, meaning that it contains the rows, columns, and cells that will hold data. In HTML, all of these components must be created. The first step in entering data into the table is to add rows using the table row element: <tr>. <table> <tr> </tr> <tr> </tr> </table> In the example above, two rows have been added to the table.
And Operator
In previous exercises, we chained multiple media features of the same type in one media query by using the and operator. It allowed us to create a range by using min-width and max-width in the same media query. The and operator can be used to require multiple media features. Therefore, we can use the and operator to require both a max-width of 480px and to have a min-resolution of 300dpi. For example: @media only screen and (max-width: 480px) and (min-resolution: 300dpi) { /* CSS ruleset */ } By placing the and operator between the two media features, the browser will require both media features to be true before it renders the CSS within the media query. The and operator can be used to chain as many media features as necessary.
What is the Box Model?
In some of the past exercises, you've unknowingly seen aspects of the box model. For example, when you set the background color of an element, you may have noticed that the background color was applied not only to the area directly behind the element, but also to the area to the right of the element. In another exercise, you learned how to align the text. How did the browser know how to align the text? All HTML elements live within a box. Elements on a web page are understood by the browser as "living" inside of a container, or a box. This is what is meant by the box model. When you changed the background color of an element, you changed the background color of its entire box. When you aligned text, the text was aligned relative to the element's entire box. To truly create custom websites, you'll have to understand the box model. In this unit, you'll learn about the following aspects of the box model: 1. The dimensions of an element's box 2. The borders of an element's box 3. The content within an element's box 4. The area around all four sides of an element's box
Table Head
In the last exercise, the table's headings were kept inside of the table's body. When a table's body is sectioned off, however, it also makes sense to section off the table's headings using the <thead> element. <table> <thead> <tr> <th></th> <th>Saturday</th> <th>Sunday</th> </tr> </thead> <tbody> <tr> <th>Morning</th> <td rowspan="2">Work</td> <td rowspan="3">Relax</td> </tr> <tr> <th>Afternoon</th> </tr> <tr> <th>Evening</th> <td>Dinner</td> </tr> </tbody> </table> In the example above, the only new element is <thead>. The table headings are contained inside of this element. Note that the table's head still requires a row in order to contain the table headings.
Background: Repeat
In the last exercise, you probably noticed that the background image was repeated, creating a tiled background (this is the default behavior). You can control how a background image repeats with the background-repeat property. This property can take one of four values: repeat - the default value — the image will repeat horizontally and vertically. repeat-x - the background image will be repeated only along the x-axis (horizontally). repeat-y - the background image will be repeated only along the y-axis (vertically). no-repeat - the background image will not be repeated at all and will appear only once. p { background-image: url("#"); background-repeat: repeat-x; } In the example above, the paragraph's background image will repeat horizontally.
Background: Shorthand
In the last few exercises, you learned how to set a background image, its repetition pattern, and its position using three different properties. CSS allows you to set all three properties at once using a shorthand property: background. Previously, we set these three properties as follows: p { background-image: url("#"); background-repeat: no-repeat; background-position: right center; } The code in the example above can be shortened using the background property. p { background: url("#") no-repeat right center; } Note that the background property includes all of the properties that we previously styled individually: background image, repetition, and position (in that order). It's considered best practice to follow this order of values when setting the background property.
Shorthand
In the last few exercises, you learned how to set a border's style, width, and color with three different properties. CSS allows you to style all three properties at once with a shorthand property. The shorthand way of setting border style, width, and color can be achieved with the border property. Let's look at how we can decrease the amount of code bloat with this property. div.container { border-style: solid; border-width: 3px; border-color: rgb(22, 77, 100); } The code in the example above can be shortened using the border property: div.container { border: 3px solid rgb(22, 77, 100); } Note that the border property includes all of the properties that we previously styled individually: width, style, and color. It's considered best practice to follow the width-style-color order when using the border property.
Box Borders
In the last lesson, you learned how to modify the dimensions of boxes. In this lesson, you'll learn how to manipulate another box property: borders. In a previous exercise, you typed the following unexplained snippet of code into your stylesheet: * { border: 1px solid rgba(0, 0, 0, 0.3); } In this lesson, you'll learn exactly what this code means and how it can be used to help support your learning of the box model.
Why Images Matter
In the very beginning of the course, we taught you how to add images to your web page using the <img> element. While this technique is still valid, it's possible to also add images (and style them) to a website and style them using CSS techniques. The aim of this unit will be to teach you how to add images to your web page by using a variety of techniques.
Display: Flex
In the web browser, the gallery images that were arranged neatly in rows are now stacked on the left side of the webpage. The CSS display value that arranged the images, flex, has been removed. In addition to other capabilities, flex can be used to easily align multiple page elements horizontally. In the example code below, there is a div with class parent: <div class="parent"> ... </div> To make children of the div align horizontally on the webpage, in CSS we can use: .parent { display: flex; } Children elements of the div with class parent will now align horizontally. We can make sure no child element moves off the page by using flex-wrap: wrap;: .parent { display: flex; flex-wrap: wrap; } Finally, to center rows of children elements, we can use justify-content: center;: .parent { display: flex; flex-wrap: wrap; justify-content: center; }
Maintainable Code
In this unit, you'll learn about a critical skill beneficial for all web developers: organizing HTML code. Being able to clearly organize HTML code helps in the following ways: Writing clear, maintainable HTML code for yourself and for other developers. Venturing into more advanced CSS styling. In the last unit, you learned how to style color and fonts. Unfortunately, we had no way of targeting specific HTML elements. Instead, every selector we used targeted all elements of a certain type. By organizing HTML code with labels for elements, you'll learn how to style specific HTML elements at-will.
EM
Incorporating relative sizing starts by using units other than pixels. One unit of measurement you can use in CSS to create relatively-sized content is the em, written as em in CSS. Historically, the em represented the width of a capital letter M in the typeface and size being used. That is no longer the case. Today, the em represents the size of the base font being used. For example, if the base font of a browser is 16 pixels (which is normally the default size of text in a browser), then 1 em is equal to 16 pixels. 2 ems would equal 32 pixels, and so on. Let's take a look at two examples that show how em can be used in CSS. .heading { font-size: 2em; } In the example above, no base font has been specified, therefore the font size of the heading element will be set relative to the default font size of the browser. Assuming the default font size is 16 pixels, then the font size of the heading element will be 32 pixels. .splash-section { font-size: 18px; } .splash-section h1 { font-size: 1.5em; } The example above shows how to use ems without relying on the default font size of the browser. Instead, a base font size (18px) is defined for all text within the splash-section element. The second CSS rule will set the font size of all h1 elements inside of splash-section relative to the base font of splash-section (18 pixels). The resulting font size of h1 elements will be 27 pixels.
<!DOCTYPE html>
It tells the browser what type of document to expect, along with what version of HTML is being used in the document. <!DOCTYPE html> must be the first line of code in all of your HTML documents
Multiple Classes: HTML
It's also possible to label HTML elements with more than one class. How is this functionality useful? You learned that elements that share a styling (e.g. typeface) are labeled with the same class. When those same elements must also be differentiated, however, labeling with an additional class is helpful. Here is an example: <h1 class="book domestic">The Way of the Deep</h1> <h1 class="book foreign">A Night in the Sky</h1> .book { font-family: Georgia, serif; } .domestic { font-color: #0902CC; } .foreign { font-color: #B097DD; } In the example above, the HTML code uses main headings for two different book titles. In this example, all book titles must share the same typeface, so the headings are labeled with a class of book and are then styled with a typeface of Georgia. The books, however, must be differentiated based on their country of origin. To differentiate the book titles based on this information, two additional classes, domestic and foreign, are applied to the respective headings, which style the color of the heading in the CSS code. To label an HTML element with an additional class, simply include the class within the double quotes, immediately after the first class. HTML elements can be labeled with many classes, but whenever possible, it's best to limit an element to four classes at most.
CSS Declarations: Anatomy
It's not enough to simply select an HTML element in a CSS file. To actually style the element, you need to specify two things inside the body of the selector: 1. Property - the property you'd like to style of that element (i.e., size, color, etc.). 2. Value - the value of the property (i.e., 18px for size, Blue for color, etc.). Here is an example: h1 { color: Blue; } In the example above, the <h1> element has been selected. Inside of the selector's body, the heading's color property is set to a value of Blue. The heading will now appear the color blue in the browser. The line color: Blue; is referred to CSS declaration. A CSS declaration consists of a property and a value. Note that a semicolon (;) ends all declarations. Finally, the entire snippet of code in the example above is known as a CSS rule. A CSS rule consists of the selector and all declarations inside of the selector.
Border Style
It's not possible to view a box's border if the border's style has not been set. A border's style can be set with the border-style property. This property can take on one of the following values: 1. solid - border is a solid line. 2. dashed - border is a series of lines or dashes. 3. dotted - border is a series of square dots. 4. double - border is two solid black lines. 5. groove - border is a groove (or carving). 6. inset - border appears to cut into the screen. 7. outset - border appears to pop out of the screen. 8. ridge - border appears as a picture frame. 9. hidden or none - no border. Here is an example: div { border-style: solid; } In the example above, a solid black line will appear around all divs on the page.
Comments in CSS
Just like HTML, you can also leave comments in your CSS file. CSS comments begin with /* and end with */, like so: Here is an example: /* This is a comment in CSS! */ Including comments in your code is helpful for many reasons: 1. They help you (and others) understand your code if you decide to come back and review it at a much later date. 2. They allow you to experiment with new code, without having to delete old code. Here is another example: /* Paragraph Styling */ p { color: Blue; } In the example above, a comment is used to specify CSS styling for paragraphs. Here is another example: /* h1 { color: Red; } */ In the example above, a valid CSS rule has been "commented out." This practice is useful when you want to experiment with new code without having to delete old code.
Margin 2
Just like padding, what if you don't want equal margin on all four sides of the box? In that case, another version of the margin property lets you specify exactly how much margin there should be on each side of the box. Here is an example: p { margin: 6px 12px 6px 12px; } In the example above, the four values 6px 12px 6px 12px refer to the amount of margin around the box in a clockwise rotation. In order, it specifies the amount of margin on the top (6 pixels), right (12 pixels), bottom (6 pixels), and left (12 pixels) sides of the box. When this version of the margin property is used, a margin value must be specified for all four sides of the box.
Header/Navigation
Let's use Bootstrap's grid to create a simple header with navbar. In the example code below, an HTML header element with Bootstrap's predefined container class is used: <header class="container"> ... </header> Inside the header, a row is created by using a div with Bootstrap's row class: <header class="container"> <div class="row"> </div> </header> Finally, the row is cut into two parts: <header class="container"> <div class="row"> <h1 class="col-sm-4">Heading</h1> <nav class="col-sm-8 text-right"> <p>nav item 1</p> <p>nav item 2</p> <p>nav item 3</p> </nav> </div> </header> The first part consists of the h1 with Bootstrap's class col-sm-4. It will take up the first four columns on the grid. The second part consists of the nav element with class col-sm-8. It will take up the remaining eight grid columns. text-right indicates that text will be arranged on the right side of the nav.
Box Model: Content Box
Many properties in CSS have a default value and don't have to be explicitly set in the stylesheet. For example, the default font-weight of text is normal, but this property-value pair is not typically specified in a stylesheet. The same can be said about the box model that browsers assume. In CSS, the box-sizing property controls the type of box model the browser should use when interpreting a web page. The default value of this property is content-box. This is the same box model that is affected by border thickness and padding. Width + Padding + Border = Actual Rendered Width of Element's Box
Scaling: Images & Videos
Many websites contain a variety of different media, like images and videos. When a website contains such media, it's important to make sure that it is scaled proportionally so that users can correctly view it. .container { width: 50%; height: 200px; overflow: hidden; } .container img { max-width: 100%; height: auto; display: block; } In the example above, .container represents a container div. It is set to a width of 50% (half of the browser's width, in this example) and a height of 200 pixels. Setting overflow to hidden ensures that any content with dimensions larger than the container will be hidden from view. The second CSS rule ensures that images scale with the width of the container. The height property is set to auto, meaning an image's height will automatically scale proportionally with the width. Finally, the last line will display images as block level elements (rather than inline-block, their default state). This will prevent images from attempting to align with other content on the page (like text), which can add unintended margin to the images. It's worth memorizing the entire example above. It represents a very common design pattern used to scale images and videos proportionally. Note: The example above scales the width of an image (or video) to the width of a container. If the image is larger than the container, the vertical portion of the image will overflow and will not display. To swap this behavior, you can set max-height to 100% and width to auto (essentially swapping the values). This will scale the height of the image with the height of the container instead. If the image is larger than the container, the horizontal portion of the image will overflow and not display.
Relative Measurments
Modern technology allows users to browse the Internet via multiple devices, such as desktop monitors, mobile phones, tablets, and more. Devices of different screen sizes, however, pose a problem for web developers: how can we ensure that a website is readable and visually appealing across all devices, regardless of screen size? The answer: responsive design! Responsive design refers to the ability of a website to resize and reorganize its content based on: The size of other content on the website. The size of the screen the website is being viewed on. In this lesson, we'll size HTML content relative to other content on a website. You've probably noticed the unit of pixels, or px, used in websites. Pixels are used to size content to exact dimensions. For example, if you want a div to be exactly 500 pixels wide and 100 pixels tall, then the unit of px can be used. Pixels, however, are fixed, hard coded values. When a screen size changes (like switching from landscape to portrait view on a phone), elements sized with pixels can appear too small, overflow the screen, or become completely illegible. With CSS, you can avoid hard coded measurements and use relative measurements instead. Relative measurements offer an advantage over hard coded measurements, as they allow for the proportions of a website to remain intact regardless of screen size or layout.
More Fonts
New fonts are constantly being developed. Because there are so many new fonts available, it would be unrealistic to expect users to have all of them installed on their computers. Fortunately, you don't have to predict which fonts are installed on a user's computer. Many (but not all) of the new fonts that emerge on a daily basis are being centralized in directories made available for public use. For example, Google offers Google Fonts, a directory of thousands of open-source fonts that are free to use by anyone. To use these fonts, you can link to a specific Google Font in your HTML code and use it immediately in your stylesheet. Because the HTML file links directly to the Google Font, a user's browser can display the typeface you specify. This avoids having to determine whether or not that font is installed on a user's computer. To use a Google Font, you can use a <link> element, just like you did for a CSS stylesheet: <head> <link href="https://fonts.googleapis.com/css?family=Raleway" type="text/css" rel="stylesheet" > </head> In the example above, the href attribute is set to the following URL, which was retrieved from Google Fonts: https://fonts.googleapis.com/css?family=Raleway The URL in the example above specifies the Raleway typeface from Google Fonts. You can use the new font just as you would use any other font: h1 { font-family: Raleway, Georgia, serif; } You now have access to thousands of new, modern, free-to-use fonts!
Active
Next, locate the .contact-btn a:active selector. :active is a psuedo-class selector, which we use to style an element only while it's being clicked. Add the following CSS to the .contact-btn a:active selector: top: 2px; This will cause the Contact button to move down slightly while being clicked, simulating a real-life button being pushed.
Using Float
Nice work! The navbar is starting to come together nicely. It would be even better if we could get the Contact button to fill in the empty corner on the bottom right. To achieve this, we can use the CSS float property. By using float, we have the option of floating elements left or right. Consider the example code below. The class selector, .logo, floats left, and the id selector #search-bar floats right: .logo { float: left; } #search-bar { float: right; }
Anchor Elements
Nice work! The webpage is starting to come together. What if you wanted to link users to a different webpage? The HTML anchor element makes it possible to do this with a single click. <a href="http://google.com"> Click here for Google!</a> Anchor elements use an attribute to link users to websites. Attributes customize the behavior or appearance of HTML elements. Anchor elements use the href attribute, which specifies the webpage to link to. In the example above, the text "Click here for Google!" links to http://google.com. IMPORTANT: Web addresses, such as http://google.com, have a technical name: URL. Next, use an anchor element to link the word "list" to the URL cities.html. Here is a <a href="cities.html">list</a> of cities where you can find us. Note: cities.html is within the Ollie site folder, so we do not need to specify a full URL When you have added the anchor element, click Run. In the web browser, you will now see the word "list" underlined, indicating that the word is a link. Click on the link to test it out!
Text Alignment
No matter how much styling is applied to text (typeface, size, weight, etc.), text always appears on the left side of the browser. To move, or align, text, we can use the text-align property. Here is an example: h1 { text-align: right; } The text-align property can be set to one of the following three values: left - aligns text to the left hand side of the browser. center - centers text. right - aligns text to the right hand side of the browser. Later in the course, you'll learn exactly how the browser positions HTML elements by default, which will help you understand how the browser "aligns" text, since "align" is a relative term. For now, it's enough to know that text can be moved to the left, center, or right side of the web page.
The New Box Model
Now that you know about the new box model, let's actually implement it in the browser. Here is an example: * { box-sizing: border-box; } It's that simple! In the example above, the universal selector (*) targets all elements on the web page and sets their box model to the border-box model.
Class Selectors 1: CSS
Now that you know how to label HTML elements with a class, we can style elements belonging to the same class at once. How exactly do you select them in CSS, though? To style elements of the same class, you can use a class selector in the stylesheet. Here is an example: .science { font-family: Georgia, Times, serif; color: #A3B4C5; text-transform: uppercase; } Class selectors begin with a period (.) and are immediately followed by the name of the class. In the example above, all elements with a class of science will have their typeface, color, and letter case modified. As you learn more about web development, you'll notice that it's very common to style groups of elements using classes. In fact, you're more likely to see classes more often than you see IDs. While IDs still play a critical role when you move into languages like JavaScript, classes are by far the most commonly used for styling groups of elements.
ID Selectors: CSS
Now that you know how to label HTML elements with an ID, we can style that specific element in the stylesheet. In a previous lesson, you learned how to target HTML elements with element selectors, like so: p { font-size: 10px; font-color: #A091DD; } Remember, however, that an element selector like the one in the example above would targets all paragraphs on the web page. In the example above, all paragraphs are styled to have a font size of 10 pixels and a font color of #A091DD. To style a specific element labeled with an ID, you can use an ID selector in the stylesheet. Here is an example: #botswana { background-color: #56ABFF; } In the example above, the HTML element with an ID of botswana is targeted with the ID selector #botswana. All ID selectors begin with the octothorpe character: #. The value of the ID immediately follows the octothorpe. Once you've correctly targeted the element, you can proceed to style it as usual
Divs + Classes
Now that you know how to organize code into sections using divs, we can start labeling divs with classes instead, rather than labeling individual elements with classes. This does not mean that labeling individual elements with classes is no longer useful. Even when divs are labeled with classes, there will be many other times when an individual element will need to be labeled with a class. Here is an example: <div class="container"> <h1 class="title">Alice In Wonderland</h1> <p> ... </p> </div> div.container { background-color: rgb(252, 255, 205); font-family: Roboto, Helvetica, sans-serif; } h1.title { color: #0D1A2F; } In the example above, a heading and paragraph are contained within a div that has a class of container. In the stylesheet, the background color and typeface of the div have been styled. Divs are intended to contain other HTML elements, not raw text. Does it make sense to style a div directly then? When a div is styled, all elements inside of the div will inherit the styling applied to the div. This example illustrates how easy it is to style sections of a web page using div. Note: The example above uses a class called container. Chances are that you'll frequently see this class name as you learn more about web development.
font-family
One of the most effective ways to enhance the look and feel of a website is by changing the font. In CSS, font is managed using the font-family property: h1 { font-family: Georgia, serif; } Above, the font-family property of the h1 selector is set to the value of Georgia, with serif as a fallback font. Fallback fonts are included in case a visitor's web browser does not support the first font. Sometimes, more than one fallback font is included.
On The Grid
One of the reasons Bootstrap and frameworks like it are so popular is because they offer grids. A grid makes it possible to organize HTML elements using preconfigured columns. Using a grid, you can customize responsive page layouts quickly and reliably. The Bootstrap grid contains 12 equal-sized columns, as seen in the diagram on the right. HTML elements are arranged to span different numbers of columns in order to create custom page layouts. Instructions In the diagram, observe the following: Bootstrap's grid columns are represented by 12 vertical bars. The boxes represent HTML elements. The words "container", "jumbotron", "col-sm-6" and "col-sm-3" refer to Bootstrap classes. The element with class "jumbotron" spans the entire width of the webpage, beyond the borders of the grid. Elements inside the second "container", such as "col-sm-6" and "col-sm-3" are contained within the grid columns. Elements labeled "col-sm-3" take up three grid columns; elements labeled "col-sm-6" take up six grid columns.
Position: Relative
One way to modify the default position of an element is by setting its position property to relative. This value allows you to position an element relative to its default static position on the web page. .box-bottom { background-color: DeepSkyBlue; position: relative; } Although the code in the example above instructs the browser to expect a relative positioning of the div, it does not specify where the div should be positioned on the page. Here is an example: .box-bottom { background-color: DeepSkyBlue; position: relative; top: 20px; left: 50px; } In the example above, the div has been positioned using two of the four offset properties. The valid offset properties are: top - moves the element down. bottom - moves the element up. left - moves the element right. right - moves the element left. In the example above, the div will be moved down 20 pixels and to the right 50 pixels from its default static position. The image below displays the new position of the box. The dotted line represents where the statically positioned (default) box was positioned. Units for offset properties can be specified in pixels, ems, or percentages. Note that offset properties will not work if the position of the element is not set to relative.
Named Colors
Over the past few exercises, you've seen CSS examples that use colors like Red, Blue, or Cyan. In CSS, these colors are technically known as named colors. There are a total of 147 named colors. At this point, you might be wondering if you are expected to memorize the list of 147 named colors that CSS offers. Fortunately, you don't have to! There are plenty of available resources on the Internet that list all of the named colors in CSS, like the one we linked you to above. If you're ever in need of a named color, a quick Google search will yield the results you are looking for.
Table Body
Over time, a table can grow to contain a lot of data and become very long. When this happens, the table can be sectioned off so that it is easier to manage. Long tables can be sectioned off using the table body element: <tbody>. The <tbody> element should contain the all of the table's data, excluding the table headings (more on this in a later exercise). <table> <tbody> <tr> <th></th> <th>Saturday</th> <th>Sunday</th> </tr> <tr> <th>Morning</th> <td rowspan="2">Work</td> <td rowspan="3">Relax</td> </tr> <tr> <th>Afternoon</th> </tr> <tr> <th>Evening</th> <td>Dinner</td> </tr> </tbody> </table> In the example above, all of the table data is contained within a table body element. Note, however, that the headings were also kept in the table's body — we'll change this in the next exercise.
ALT Attribute
Part of being an exceptional web developer is making your site accessible to users of all backgrounds. Specifically, visually impaired users require more support from your web page so that they can experience the content on your page. HTML helps support visually impaired users with the alt attribute. The alt attribute is applied specifically to the <img> element. The value of alt should be a description of the image. Here is an example: <img src="#" alt="A field of yellow sunflowers" /> The alt attributes also serves the following purposes: 1. If an image fails to load on a web page, a user can mouse over the area originally intended for the image and read a brief description of the image. This is made possible by the description you provide in the alt attribute. 2. Visually impaired users often browse the web with the aid of of screen reading software. When you include the alt attribute, the screen reading software can read the image's description out loud to the visually impaired user.
Percentages: Padding & Margin
Percentages can also be used to set the padding and margin of elements. When height and width are set using percentages, you learned that the dimensions of child elements are calculated based on the dimensions of the parent element. When percentages are used to set padding and margin, however, they are calculated based only on the width of the parent element. For example, when a property like margin-left is set using a percentage (say 50%), the element will be moved halfway to the right in the parent container (as opposed to the child element receiving a margin half of its parent's margin). Vertical padding and margin are also calculated based on the width of the parent. Why? Consider the following scenario: A container div is defined, but its height is not set (meaning it's flat). The container then has a child element added within. The child element does have a set height. This causes the height of its parent container to stretch to that height. The child element requires a change, and its height is modified. This causes the parent container's height to also stretch to the new height. This cycle occurs endlessly whenever the child element's height is changed! In the scenario above, an unset height (the parent's) results in a constantly changing height due to changes to the child element. This is why vertical padding and margin are based on the width of the parent, and not the height. Note: When using relative sizing, ems and rems should be used to size text and dimensions on the page related to text size (i.e. padding around text). This creates a consistent layout based on text size. Otherwise, percentages should be used.
Color Declarations
RGB colors, hex color codes, and HSL colors offer web developers an extraordinary amount of color customization options. As these properties become more advanced, however, it's important to keep in mind that not all users browse the Internet with the same browser, let alone the same version of a given browser. How does this affect web development? Newer revisions of HTML and CSS affect older browsers. Older browsers, over time, will become dated (possibly obsolete) and not be able to support newer CSS features. For example, many older browsers do not support RGBa, HSL, or HSLa. Because of this, we must include redundant color options in our CSS code that can cater to a wide audience of different browsers. Specifically, we can add multiple CSS color declarations, just in case a user's browser can't support a certain declaration. Here is an example: h1 { color: rgb(22, 34, 88); color: rgba(22, 34, 88, 0.4); } In CSS, the latter of multiple declarations takes priority. In the example above, if the user's browser supports rgba(), then that color will be applied to the heading. If it does not, then CSS will use the first rgb() color declaration, as a backup. Using redundant declarations allow you to support as many users as possible across multiple versions of different Internet browsers.
Table Data
Rows aren't sufficient to add data to a table. Each cell element must also be defined. In HTML, you can add data using the table data element: <td>. <table> <tr> <td>73</td> <td>81</td> </tr> </table> In the example above, two data points (73 and 81) were entered in the one row that exists. By adding two data points, we created two cells of data. If the table were displayed in the browser, it would show a table with one row and two columns.
Table Borders
So far, the tables you've created have been a little difficult to read because they have no borders. In older versions of HTML, a border could be added to a table using the border attribute and setting it equal to an integer. This integer would represent the thickness of the border. <table border="1"> <tr> <td>73</td> <td>81</td> </tr> </table> The code in the example above is following is deprecated, so please don't use it. It's meant to illustrate older conventions you may come across when reading other developers' code. The browser will likely still interpret your code correct if you use the border attribute, but that doesn't mean the attribute should be used. Instead, you can achieve the same effect using CSS. table, td { border: 1px solid black; } The code in the example above uses CSS instead of HTML to show table borders.
Margin 1
So far, you've learned about the following aspects of the box model: dimensions, borders, and padding. The fourth and final aspect of the box model is margin. The margin refers to the space directly outside of the box. You can adjust this spacing with the margin property. Here is an example: p { border: 1px solid #23AD44; margin: 20px; } The code in the example above will place 20 pixels of space on the outside of the paragraph's box, on all four sides. This means that other HTML elements on the page cannot come within 20 pixels of the paragraph. An understanding of the margin property is crucial in order to later understand element positioning in the browser.
Float
So far, you've learned how to specify the exact position of an element using offset properties. If you're simply interested in moving an element as far left or as far right as possible on the page, you can use the float property. The float property can be set to one of two values: left - this value will move, or float, elements as far left as possible. right - this value will move elements as far right as possible. Here is an example: .boxes { width: 120px; height: 70px; } .box-bottom { background-color: DeepSkyBlue; float: right; } In the example above, we float the .box-bottom element to the right. This works for static and relative positioned elements. See the result of the code below: Floated elements must have a width specified, as in the example above. Otherwise, the element will assume the full width of its containing element, and changing the float value will not yield any visible results.
Range
Specific screen sizes can be targeted by setting multiple width and height media features. min-width and min-height are used to set the minimum width and minimum height, respectively. Conversely, max-width and max-height set the maximum width and maximum height, respectively. By using multiple widths and heights, a range can be set for a media query. @media only screen and (min-width: 320px) and (max-width: 480px) { /* ruleset for 320px - 480px */ } The example above would apply its CSS rules only when the screen size is between 320 pixels and 480 pixels. Notice the use of a second and keyword after the min-width media feature. This allows us to chain two requirements together. The example above can be written using two separate rules as well: @media only screen and (min-width: 320px) { /* ruleset for 320px - 479px */ } @media only screen and (min-width: 480px) { /* ruleset for > 480px */ } The first media query in the example above will apply CSS rules when the size of the screen meets or exceeds 320 pixels. The second media query will apply CSS rules when the size of the screen meets or exceeds 480 pixels, meaning that it will override the CSS rules present in the first media query. Both examples above are valid, and it is likely that you will see both patterns used when reading another developer's code.
Multiple Element Selectors
Styling with CSS would be very inefficient if you were forced to manually style the same property across many elements. For example, what if you wanted to change the color of 10 different elements to Aquamarine in CSS? Fortunately, you can select multiple elements at once so that you can save time styling a shared property. Here is an example: h1, h2, p { color: Green; } In the example above, the <h1> heading, the <h2> heading, and the paragraph (<p>) have all been styled to appear Green using a multiple element selector. A multiple element selector can save you time when you want to style the same property across many elements
Table Headings
Table data doesn't make much sense without titles to describe what the data represents. To add titles to rows and columns, you can use the table heading element: <th>. The table heading element is used just like a table data element, except with a relevant title. Just like table data, a table heading must be placed within a table row. <table> <tr> <th></th> <th scope="col">Saturday</th> <th scope="col">Sunday</th> </tr> <tr> <th scope="row">Temperature</th> <td>73</td> <td>81</td> </tr> </table> What happened in the code above? First, a new row was added to hold the three headings: a blank heading, a Saturday heading, and a Sunday heading. The blank heading creates the extra table cell necessary to align the table headings correctly over the data they correspond to. In the second row, one table heading was added as a row title: Temperature. Note, also, the use of the scope attribute, which can take one of two values: row - this value makes it clear that the heading is for a row. col - this value makes it clear that the heading is for a column. HTML code for tables may look a little strange at first, but analyzing it piece by piece helps make the code more understandable.
Styling With CSS
Tables, by default, are very bland. They have no borders, the font color is black, and the typeface is the same type used for other HTML elements. You can use CSS to style tables just like you have done in the past. Specifically, you can change style the various aspects mentioned above. table, th, td { border: 1px solid black; font-family: Arial, sans-serif; text-align: center; } The code in the example above demonstrates just some of the various table aspects you can style using the CSS properties you learned about earlier.
Position
Take a look at the block-level elements in the image below: The boxes in the image above were created with the following CSS: .boxes { width: 120px; height: 70px; } Notice the block-level elements in the image above take up their own line of space and therefore don't overlap each other. In the browser to the right you can see block-level elements also consistently appear on the left side of the browser. This is the default position for block-level elements. The default position of an element can be changed by setting its position property. The position property can take one of four values: static - the default value (it does not need to be specified) relative absolute fixed In the next few exercises, you'll learn about the values in items 2, 3, and 4 above. For now, it's important to understand that if you favor the default position of an HTML element, you don't need to set its position property. Instructions In style.css, set the position in .question to static. Notice that setting position to static does nothing. That's because static simply refers to the default behavior.
Margin 3
Take a look at the following code. What do you notice about the margin values? p { margin: 6px 12px 6px 12px; } The top and bottom values of margin are the same (6px) and the left and right value of margin are also the same (12px). Just like the padding shortcut, when you're certain that the top and bottom values for margin will equal each other, and that the left and right values for padding will also equal each other, you can use the following shortcut: p { margin: 6px 12px; } The first value, 6px, sets a margin value for the top and bottom sides of the box. The second value, 12px sets a margin value for the left and right sides of the box.
Padding 3
Take a look at the following code. What do you notice about the padding values? p { padding: 5px 10px 5px 10px; } The top and bottom values for padding are the same (5px) and the left and right values for padding are also the same (10px). When you're certain that the top and bottom values for padding will equal each other, and that the left and right values for padding will also equal each other, you can use the following shortcut: p { padding: 5px 10px; } The first value, 5px, sets a padding value for the top and bottom sides of the content. The second value, 10px sets a padding value the left and right sides of the content.
Text Transformation
Text can also be styled to appear in either all uppercase or lowercase with the text-transform property. Here is an example: h1 { text-transform: uppercase; } The code in the example above formats all <h1> elements to appear in uppercase, regardless of the case used for the heading within the HTML code. Alternatively, the lowercase value could be used to format text in all lowercase. Since text can be directly typed in all uppercase or lowercase within an HTML file, what is the point of a CSS rule that allows you to format letter case? Depending on the type of content a web page displays, it may make sense to always style a specific element in all uppercase or lowercase letters. For example, a website that reports breaking news may decide to format all <h1> heading elements such that they always appear in all uppercase, as in the example above. It would also avoid uppercase text in the HTML file, which could make code difficult to read.
Line Height
Text on a web page must also be easy to read. When text is styled to appear larger, the vertical spacing between lines of text can decrease, creating text that is difficult to read, particularly in paragraphs. To avoid this problem, you can modify the spacing between lines of text with the line-height property. Here is an example: p { line-height: 1.5em; } When the line height of an element is modified, you are manipulating the leading (pronounced "ledding") of the font. When the line height is increased, the spacing between lines of text increases, which can make text easier to read. The line height can be modified using pixels or ems, but the unit of ems is preferred, since ems offer a spacing relative to the size of the text on the page.
Images
The <img> element lets you add images to a web page. This element is special because it does not have a closing tag, it only has an opening tag. This is because the <img> element is a self-closing element. here is an example: <img src="https://www.example.com/picture.jpg" /> Note that the <img> element has a required attribute called src, which is similar to the href attribute in links. In this case, the value of src must be the URL of the image. Also note that the end of the <img> element has a forward slash /. This is required for a self-closing element.
Working With Margin
The CSS margin property controls the space between different HTML elements on a webpage. Use margin to bring page elements closer together or to move them further apart. The CSS below ensures 2rems of space between elements with the class answer and surrounding page elements. .answer { margin: 2rem; }
Working With Padding
The CSS padding property controls the empty space between the page element's content and its border. Increasing a page element's padding makes the space around the content more spacious, while decreasing it makes the space more compact. p { padding: 20px; } The CSS above would give paragraph elements a padding of 20px.
Working With Position
The CSS position property enables you to position HTML elements in exact locations on a webpage. One useful value for this property is relative. This value positions page elements on a webpage relative to where they would normally appear. By first setting position: relative;, you can then use the CSS properties top, left, bottom, and right to shift an element away from where it would have normally appeared on the page. The code snippet below moves a div with the class container 10px away from the up and 20px away from the left side of the page. .container { position: relative; top: 10px; left: 20px; } Ever click a button on a webpage that seemed to move down and then back up like a real-life button? We can implement this trick using the position property.
Create a Border
The border property can be used to visually define a page element's outer edge. In CSS, the border property's value requires three parts: thickness: Sets the thickness of the border, using pixels, ems, or rems. type: Sets the border type. Common options are solid, dotted, and dashed. There are many others. color: sets the border's color, using named colors, HEX, or RGB values. The CSS below gives a paragraph element a solid black border that is 2 pixels thick: p { border: 2px solid black; }
Table Footer
The bottom part of a long table can also be sectioned off using the <tfoot> element. <table> <thead> <tr> <th>Quarter</th> <th>Revenue</th> <th>Costs</th> </tr> </thead> <tbody> <tr> <th>Q1</th> <td>$10M</td> <td>$7.5M</td> </tr> <tr> <th>Q2</th> <td>$12M</td> <td>$5M</td> </tr> </tbody> <tfoot> <tr> <th>Total</th> <td>$22M</td> <td>$12.5M</td> </tr> </tfoot> </table> In the example above, the footer contains the totals of the data in the table. Footers are often used to contain sums, differences, and other data results.
Page Layout
The box model is the first step in understanding how the browser lays out HTML elements. Visually appealing websites, however, are often the result of well positioned elements. In this unit, you'll learn how to position HTML elements in order to gain more control of a web page's layout.
Class Selectors 2: CSS
The class selector targets all elements of a particular class. It's possible, however, for multiple elements on a web page to share a specific styling, but for one of those elements to differ slightly. For example, a heading and a paragraph (both with a class of breaking) may need to share the same typeface, but the paragraph may require a styling better suited for paragraphs, as in the following example. Here is an example: .breaking { font-family: Georgia, Times, serif; } p.breaking { line-height: 1.3em; } The example above uses a new selector: p.breaking. What's the difference between the .breaking and p.breaking selectors? The .breaking selector targets all elements with a class of breaking. The p.breaking selector targets only <p> elements with a class of breaking. This type of selector allows you to be even more specific about a particular element's styling, even when that element must share some styling with other elements. Unless otherwise specified, the rest of this course will use the element.class selector syntax.
Border Color
The color of a border can also be customized with the border-color property. Here is an example: div.container { border-style: solid; border-width: 3px; border-color: rgb(22, 77, 100); } The border-color property accepts colors in the various formats you learned about earlier: named colors, RGB(a) colors, and hex colors. It's common to use hex colors for borders, but you'll likely also come across RGB(a) colors as well.
HSL
The current revision of CSS, CSS3 (at the time of this writing), introduces a new way to specify colors using HSL colors. HSL stands for Hue, Saturation, and Lightness. Specifically, this is what each means: 1. Hue - the technical term that describes what we understand as "color." In HSL, hue is represented on a color wheel. It can take on values between 0 and 360. 2. Saturation - the amount of gray in a given color. In HSL, saturation is specified using a percentage between 0% and 100%. The percentage 0% represents a shade of gray, whereas 100% represents full saturation. 3. Lightness - the amount of white in a given color. Similar to saturation, lightness is specified using a percentage between 0% and 100%. The percentage 0% represents black, whereas 100% represents white. 50% is normal. You can use HSL colors in your CSS like this: h1 { color: hsl(182, 20%, 50%); } Notice that using HSL is very similar to using RGB. Note: Because HSL is a part of CSS3, older browsers may not support it. In a later exercise, you'll learn how to work around support issues for colors.
Why Divs?
The div is one of the most commonly used elements in all of HTML. Modern web pages make extensive use of the div, and learning how to use divs for organization and styling is a critical skill for all web developers. Moving forward, this course will make more use of the div so that you can master it and become more familiar with this important element.
Clear
The float property can also be used to float multiple elements at once. However, when multiple floated elements have different heights, it can affect their layout on the page. Specifically, elements can "bump" into each other and not allow other elements to properly move to the left or right. The clear property specifies how elements should behave when they bump into each other on the page. It can take on one of the following values: left — the left side of the element will not touch any other element within the same containing element. right — the right side of the element will not touch any other element within the same containing element. both — neither side of the element will touch any other element within the same containing element. none — the element can touch either side. Here is an example: div { width: 200px; float: left; } div.special { clear: left; } In the example above, all divs on the page are floated to the left side. The div with class special did not move all the way to the left because a taller div blocked its positioning. By setting its clear property to left, the special div will be moved all the way to the left side of the page.
HTML (Hypertext Markup Language)
The language used to create the web pages we visit everyday
Why change the box model?
The last three lessons focused on the most important aspects of the box model: box dimensions, borders, padding, and margin. The box model, however, has an awkward limitation regarding box dimensions. This limitation is best illustrated with an example. <h1>Hello World</h1> h1 { border: 1px solid black; height: 200px; width: 300px; padding: 10px; } In the example above, a heading element's box has solid, black, 1 pixel thick borders. The height of the box is 200 pixels, while the width of the box is 300 pixels. A padding of 10 pixels has also been set on all four sides of the box's content. Unfortunately, under the current box model, the border thickness and the padding will affect the dimensions of the box. The 10 pixels of padding increases the height of the box to 220 pixels the width to 320 pixels. Next, the 1 pixel thick border increases the height to 221 pixels and the width to 321 pixels. Under this box model, the border thickness and padding are added to the overall dimensions of the box. This makes it difficult to accurately size a box. Over time, this can also make all of a web page's content difficult to position and manage. In this brief lesson, you'll learn how to use a different technique that avoids this problem altogether.
Margin: Auto
The margin property also lets you center content, if you follow certain requirements. Take a look at the following example. div.headline { margin: auto; } When the margin property is set to auto, the element being styled will center in the page. In theory, the div in the example above should center on the page, but it doesn't. Why? In order to center an element, a width must be set for that element. Otherwise, the width of the div will be automatically set to the full width of its containing element, like the <body>, for example. It's not possible, therefore, to center an element that takes up the full width of the page. Here is an example: div.headline { width: 400px; margin: auto; } In the example above, the width of the div is set to 400 pixels, which is less than the width of the page's body. This will cause the div to center properly on the page. Note: When margin: auto is used, an element will center relative to its container. For example, the div in the example above was centered relative to the width of the body. If the div was contained in larger div, the smaller div would center relative to the width of the larger div. This is important to keep in mind when attempting to center nested elements, like divs.
More Margins
The margin property creates space on all sides of a page element. It's also possible to set separate margin spacings on each side of an element. Additional margin properties: margin-top: Sets the top margin. margin-bottom: Sets the bottom margin. margin-left: Sets the left margin. margin-right: Sets the right margin. Note: Below we will change margin properties for a div that encloses HTML figure elements. Figures are used to organize visuals, such as photos and diagrams.
color
The new font looks great! However, black is not your only option when it comes to font color. In CSS, the color property sets the color of a CSS selector's font: h1 { color: red; } CSS comes equipped with 140 named colors, such as red, used above. For many situations, these named colors will suffice. However, web developers who want to get even more exact with their color choices can use hexadecimal and RGB color values. Hexadecimal color (#RRGGBB): Hexadecimal values that represent mixtures of red, green and blue. For example, red can be expressed with the hexadecimal value of #FF0000: the value ff represents red, 00 represents green, and 00 represents blue. RGB (Red, Green, Blue) colors: Color created by three numbers representing red, green, and blue. When mixed together, the three values create a specific color. For example: purple can be represented as rgb(128,0,128).
Serif vs Sans Serif
The practice of typography has been around for centuries! Over time, typographers have refined their craft and have developed many different typefaces, which has allowed them, in some cases, to classify them as one of the following two types: serif fonts and sans-serif fonts. 1. Serif - the letters in these fonts have extra details on the ends of each letter. Examples include fonts like Times New Roman or Georgia, among others. 2. Sans-Serif - the letters in these fonts do not have extra details on the ends of each letter. Instead, letters have straight, flat edges. Some examples include Arial or Helvetica.
Rem
The second relative unit of measurement in CSS is the rem, coded as rem. Rem stands for root em. It acts similar to em, but instead of checking parent elements to size font, it checks the root element. The root element is the <html> tag. Most browsers set the font size of <html> to 16 pixels, so by default rem measurements will be compared to that value. To set a different font size for the root element, you can add a CSS rule. html { font-size: 20px; } h1 { font-size: 2rem; } In the example above, the font size of the root element, <html>, is set to 20 pixels. All subsequent rem measurements will now be compared to that value and the size of h1 elements in the example will be 40 pixels. One advantage of using rems is that all elements are compared to the same font size value, making it easy to predict how large or small font will appear. If you are interested in sizing elements consistently across an entire website, the rem measurement is the best unit for the job. If you're interested in sizing elements in comparison to other elements nearby, then the em unit would be better suited for the job.
font-size
The size of text has an impact on how users experience a website. The font-size property sets the size of an HTML element's text. h1 { font-size: 60px; } In the CSS above, font-size is set to 60px. In CSS, size can be assigned in pixels (px), rems, or ems. pixel (px): Standard unit of measurement for sizing fonts and other HTML elements. rem: Represents the default font size for the web browser. Rems can be used to ensure that HTML elements scale in proportion to each other on various web browsers and screen sizes. On most web browsers, 1rem is equivalent to 16px, 2rem is equivalent to 32px (a doubling), 3rem is equivalent to 48px (a tripling) and so on. em: A relative value that changes in proportion to the size of the parent element. For example, if a parent element has font-size: 20px;, child elements with font-size: 1em; would be equivalent to 20px. Child elements with font-size: 0.5em; would be equivalent to 10px (a halving) and so on. We will primarily explore px and rem values since these are the most commonly used today.
Padding 1
The space between the contents of a box and the borders of a box is known as padding. In CSS, you can modify this space with the padding property. Here is an example: p { border: 3px solid #A2D3F4; padding: 10px; } The code in the example will put 10 pixels of space between the content of the paragraph (the text) and the box borders, on all four sides. The padding property is particularly useful at making text easier to read when the text has a border around it. Note: In the last couple of lessons, you learned how to set the width and height of a box. When padding is set for a box (as in the example above) it will be added to the width and height of a box, increasing the dimensions of the box. We'll learn how to avoid this problem in the next lesson.
Font Size 2
There are three units of measurement for font size: 1. px - Represents the unit of pixels. The display of a computer monitor can be measured in pixels. A pixel is a small point on the display. How small? Most computer monitors have a resolution of 72 pixels per inch, so a pixel represents about 1/72nd of an inch. Pixels are sometimes also referred to as points. Pixels are used to set the exact size of an element, in this case, text. p { font-size: 18px; } 2. ems - Pronounced just as it looks, "em." An em is equal to the width of the letter "m". Ems are a relative unit of measurement. They change the size of text relative to the parent element's size of text. p { font-size: 1.3em; } 3. % - Percentages are also a relative unit of measurement. The default size of text in web browsers is 16 pixels, or 16px. When percentages are used, they set the size of text relative to this default size. For example, setting the font size to 200% would be equivalent to setting it to 32px. p { font-size: 150%; }
Lists
There are two types of lists in HTML, there is the ordered list (numbers) and the unordered list (bullets). Often times, it's better to display certain types of content in an easy-to-read list.
The Universal Selector
There's a special selector that can instantly select every single element on the web page: the universal selector. Here is an example: * { font-family: Arial; } In the example above, the universal selector, *, is used to select every element on the page and set the font to Arial. What makes the universal selector so special? When all elements on a web page require the same styling, it's often more efficient to set that styling using the universal selector. Afterwards, you can modify (or remove) that styling for specific elements that don't require it. In a later lesson, you'll use the universal selector to help you understand how HTML elements are laid out within the browser and how to position those elements.
Hex Colors
There's an additional way to specify colors in CSS: hexadecimal color codes, often referred to as "hex color codes" for short. Hex color codes also offer 16,777,216 color options, but they follow a different syntax. When specifying an RGB color mixture, the values are in base 10. Hex color codes, however, use base 16, or hexadecimal base (hence the name), to specify color mixtures. Here is an example: h1 { color: #09AA34; } When read from left to right, each group of two characters responds to a value for red, green and blue, respectively. In the example above, 09 refers to the value for red, AA refers to the value for green, and 34 refers to the value for blue. All hex color codes begin with a # character. Is there a difference between RGB values and hex color codes? Not really. RGB values and hex color codes are different ways to represent the same thing: color. It's possible to convert back and forth between RGB values and hex color codes (color pickers often help with this conversion). Note: When a hex color code is composed of entirely of the same characters, the hex color can be abbreviated, like so: h1 { color: #FFFFFF; color: #FFF; /* This is the same color as above */ } h2 { color: #AA33BB; color: #A3B; /* This is the same color as above */ }
Adding Images
To add images to a webpage, use the HTML image element: <img src="https://s3.amazonaws.com/codecademy-content/projects/make-a-website/lesson-1/bikes1.jpg"/> Just like websites have URLs, images on the web also have URLs. Image URLs typically end with the .jpg or .png file extension. The src attribute sets the source for an image element. Image elements are self-closing, which means they do not need a closing tag. Let's use an image element to add a photograph to our webpage.
Links
To add links do this: <a href="insert link here">Title of link</a>
Background: Size
To modify a background image's size, you can use the background-size property. This exercise will focus on two of the most common values of the background-size property: cover - expands the image as large as possible to cover the full width or height of a container. If the dimensions of the container (say, a div) are larger than the dimensions of the image, the image will become distorted. This value is best for images that don't communicate important content to the user, like background images. contain - expands the image as large as possible, but the image will be letterboxed, which means it won't cover the full width or height of a container. div.header { height: 400px; width: 100%; background: url("#") no-repeat right center; background-size: cover; } In the example above, the background image will expand to cover the full size of the div.
Percentages: Height & Width
To size non-text HTML elements relative to their parent elements on the page you can use percentages. Percentages are often used to size box-model values, like width and height, padding, border, and margins. They can also be used to set positioning properties (top, bottom, left, right). To start, let's size the height and width of an element using percentages. .main { height: 300px; width: 500px; } .main .subsection { height: 50%; width: 50%; } In the example above, .main and .subsection each represent divs. The .subsection div is nested within the .main div. Note that the dimensions of the parent div (.main) have been set to a height of 300 pixels and a width of 500 pixels. When percentages are used, elements are sized relative to the dimensions of their parent element (also known as a container). Therefore, the dimensions of the .subsection div will be 150 pixels tall and 250 pixels wide. Be careful, a child element's dimensions may be set erroneously if the dimensions of its parent element aren't set first. Note: Because the box model includes padding, borders, and margins, setting an element's width to 100% may cause content to overflow its parent container. While tempting, 100% should only be used when content will not have padding, border, or margin.
CSS Class Selectors
Up to this point, we've used CSS to select an HTML element by its tag name only. However, we can use class selectors to target classes of HTML elements. Consider the HTML below: <div class="header"> <h2>Heading</h2> <p>Paragraph</p> </div> Here, the div is the parent element and the h2 and p are children. CSS styles applied to the header class selector will automatically apply to the h2 and the p. Here's a refresher on parent and child elements. In CSS, class selectors can be identified by a dot . followed by the class name, as seen below: .header { color: #ffffff; } As a result of this code, child elements of divs with the header class will have a font color of #ffffff (white). Below, we will use a CSS class selector to style more than one HTML element at once.
Breakpoints
We know how to use media queries to apply CSS rules based on screen size and resolution, but how do we determine what queries to set? The points at which media queries are set are called breakpoints. Breakpoints are the screen sizes at which your web page does not appear properly. For example, if we want to target tablets that are in landscape orientation, we can create the following breakpoint: @media only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) { /* CSS ruleset */ } The example above creates a screen size range the size of a tablet in landscape mode and also identifies the orientation. However, setting breakpoints for every device imaginable would be incredibly difficult because there are many devices of differing shapes and sizes. In addition, new devices are released with new screen sizes every year. Rather than set breakpoints based on specific devices, the best practice is to resize your browser to view where the website naturally breaks based on its content. The dimensions at which the layout breaks or looks odd become your media query breakpoints. Within those breakpoints, we can adjust the CSS to make the page resize and reorganize. By observing the dimensions at which a website naturally breaks, you can set media query breakpoints that create the best possible user experience on a project by project basis, rather than forcing every project to fit a certain screen size. Different projects have different needs, and creating a responsive design should be no different.
Linking the CSS File
We successfully separated structure (HTML) from styling (CSS), but why does the web page look continue to look so bland? The CSS code now lives in a separate CSS file called style.css — shouldn't that have worked without issue? Not exactly. When HTML and CSS code are in separate files, the HTML file must know exactly where the CSS code is kept, otherwise, the styling can't be applied the web page. In order to apply the styling to the web page, we'll have to link the HTML file and the CSS file together. You can use the <link> element to link the HTML and CSS files together. The <link> element must be placed within the head of the HTML file. It is a self-closing tag and requires the following three attributes: 1. href - like the anchor element, the value of this attribute must be the address, or path, to the CSS file. 2. type - this attribute describes the type of document that you are linking to (in this case, a CSS file). The value of this attribute should be set to text/css. 3. rel - this attribute describes the relationship between the HTML file and the CSS file. Because you are linking to a stylesheet, the value should be set to stylesheet. When linking an HTML file and a CSS file together, the <link> element will look like the following: <link href="https://www.codecademy.com/stylesheets/style.css" type="text/css" rel="stylesheet"> Note that in the example above the path to the stylesheet is a URL: https://www.codecademy.com/stylesheets/style.css Specifying the path to the stylesheet using a URL is one way of linking a stylesheet. If the CSS file is stored in the same directory as your HTML file, then you can specify a relative path instead of a URL, like so: <link href="/style.css" type="text/css" rel="stylesheet"> Using a relative path is very common way of linking a stylesheet.
Element Selectors
We've discussed styling HTML elements using CSS, but how is it actually done? To style an HTML element using CSS, you must first select that element in the CSS file. For example, to style a <p> element, the syntax to select it using CSS is: p { } In the example above, all paragraph elements are selected using a CSS selector. The selector (in this case) is p. Note that the CSS selector essentially matches the HTML tag for that element, but without the angle brackets. Note: The p selector in the example above will select all <p> elements on the web page. Later in this course, you'll learn how to use more specific CSS selectors so that you can select any element you want.
Spanning Columns
What if the table contains data that spans multiple columns? For example, a personal calendar could have events that span across multiple hours, or even multiple days. Data can span columns using the colspan attribute. The attributes accepts an integer (greater than or equal to 1) to denote the number of columns it spans across. <table> <tr> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> </tr> <tr> <td colspan="2">Out of Town</td> <td>Back in Town</td> </tr> </table> In the example above, the data Out of Town spans the Monday and Tuesday table headings using the value 2 (two columns). The data Back in Town appear only under the Wednesday heading.
Padding 2
What if you don't want all four sides of a box's content to have equal padding? In that case, another version of the padding property lets you specify exactly how much padding there should be on each side of the content. Here is an example: p { border: 3px solid #XXXXXX; padding: 5px 10px 5px 10px; } In the example above, the four values 5px 10px 5px 10px refer to the amount of padding in a clockwise rotation. In order, it specifies the amount of padding on the top (5 pixels), right (10 pixels), bottom (5 pixels), and left (10 pixels)sides of the content. When this version of the padding property is used, a padding value must be specified for all four sides of the content.
Border Width 2
What if you don't want the border thickness to be the same on all four sides? In that case, another version of the border-width property allows you to specify the width for each side of the border. Here is an example: p { border-style: solid; border-width: 3px 1px 2px 1px; } The values in the example above refer to the border width in clockwise order (top: 3 pixels, right: 1 pixel, bottom: 2 pixels, left: 1 pixel).
Background: Position
When a background image is not repeated, its position can be modified with the background-position property. p { background-image: url("#"); background-repeat: no-repeat; background-position: right center; } A background image is positioned using a 3 by 3 grid (three rows, three columns), meaning there are 9 total possible positions for the image: left top - top left corner of the element's box. center top - top center of the element's box. right top - top right corner of the element's box. left center - left column, center row. center center - the center of the element's box. right center - right column, center row. left bottom - bottom left corner of the element's box. center bottom - bottom center of the element's box. right bottom - bottom right corner of the element's box. Note that the values are in pairs. p { background-image: url("#"); background-repeat: no-repeat; background-position: right top; } In the example above, the background image is not repeated. It's positioned in the top right corner of the element's box. Note: When setting this property, if only one value is specified, the second value will default to center.
Position: Fixed
When an element's position is set to absolute, as in the last exercise, the element will scroll out of view when a user scrolls. We can fix an element to a specific position on the page (regardless of user scrolling) by setting its position to fixed. Here is an example: .box-bottom { background-color: DeepSkyBlue; position: fixed; top: 20px; left: 50px; } In the example above, the div will remain fixed to its position no matter where the user scrolls on the page, like in the image below: This technique is often used for navigation bars on a web page.
Z-Index
When boxes on a web page have a combination of different positions, the boxes (and therefore, their content) can overlap with each other, making the content difficult to read or consume. .box-top { background-color: Aquamarine; } .box-bottom { background-color: DeepSkyBlue; position: absolute; top: 20px; left: 50px; } In the example above, the .box-bottom div ignores the .box-top div and overlaps it as a user scrolls. The z-index property controls how far "back" or how far "forward" an element should appear on the web page. The z-index property accepts integer values. Depending on their values, the integers instruct the browser on the order in which elements should be displayed on the web page. Here is an example: .box-top { background-color: Aquamarine; position: relative; z-index: 2; } .box-bottom { background-color: DeepSkyBlue; position: absolute; top: 20px; left: 50px; z-index: 1; } In the example above, we set the .box-top position to relative and the z-index to 2. We changed position to relative, because the z-index property does not work on static elements. The z-index of 2 moves the .box-top element forward, because it is greater than the .box-bottom z-index, 1. See the example image below: In the image above, you can see the top box is moved in front of the bottom box.
Responsive Web Design
When someone visits a website, it's possible they are viewing it on a phone, tablet, computer, or even a TV monitor. Because screen sizes can vary greatly across different devices, it's important for websites to resize and reorganize their content to best fit screens of all sizes. When a website doesn't respond to different screen sizes, the website may look odd or become indecipherable on certain devices. This usually occurs on smaller screens, like phones. When a website responds to the size of the screen it's viewed on, it's called a responsive website. Because websites can be displayed on thousands of different screen sizes, they must be able to respond to a change in screen size and adapt the content so that users can access it.
Line Height Anatomy
When the line-height property of an element is modified, the leading is increased, resulting in an increase of the vertical spacing between lines of text.
Overflow
When the value of the max-height property is set too low, the contents will spill outside of the box. How can we ensure that this doesn't happen? The overflow property controls what happens to content when it spills, or overflows, outside of its box. It can be set to one of the following values: hidden - when set to this value, any content that overflows be hidden from view. scroll - when set to this value, a scrollbar will be added to the element's box so that the rest of the content can be viewed by scrolling. Here is an example: p { min-width: 300px; max-width: 600px; min-height: 150px; max-height: 300px; overflow: scroll; } In the example above, minimum and maximum widths and heights have been set. If any of the paragraph content overflows (perhaps a user resizes their browser window), a scrollbar will appear so that users can view the rest of the content.
Background: Attachement
With the background-attachment property, you can specify whether or not a background image should remain at one position on the web page or whether it should move up and down as the user scrolls through a web page. The background-attachment property can take one of two values: scroll - this value allows the image to move up and down as a user scrolls on the web page (this is the default value). fixed - this value pins the image's position on the page. p { background: url("#") no-repeat right center; background-attachment: fixed; } In the example above, the background image will remained fixed as a user scrolls through the web page.
IDs: HTML
With the proper labels, we can style individual HTML elements! Specifically, we can label HTML elements with a unique identifier, or ID. We can then style that specific element in the stylesheet. To label an element with an ID, we can use the id attribute on an HTML element. Here is an example: <h1 id="botswana">Botswana</h1> In the example above, the heading is labeled with an id of botswana. What purpose do IDs serve? IDs are intended to label unique elements in an HTML file. No two HTML elements should ever share the same ID — that would defeat the purpose of a unique identifier!
Word Spacing
You can also increase the spacing between words in a body of text, technically known as word spacing. To do so, you can use the word-spacing property: h1 { word-spacing: 0.3em; } The default amount of space between words is usually 0.25em. In the example above, the word spacing is set to 0.3em, which represents an increase of only .05em in word spacing. It's not common to increase the spacing between words, but it may help enhance the readability of bolded or enlarged text. Note, again, that the preferred unit is ems.
Font Style
You can also italicize words with the font-style property. Here is an example: h3 { font-style: italic; } The italic value causes text to appear in italics. The font-style property also has a normal value, for the same reasons discussed in the previous exercise.
Height: Minimum & Maximum
You can also limit the minimum and maximum height of an element. min-height - this property ensures a minimum height for an element's box. max-height - this property ensures a maximum height for an element's box. Here is an example: p { min-height: 150px; max-height: 300px; } In the example above, the height of all paragraphs will not shrink below 150 pixels and the height will not exceed 300 pixels. What will happen to the contents of an element's box if the max-height property is set too low? It's possible for the content to spill outside of the box, resulting in content that is not legible. You'll learn how to work around this issue in the next exercise.
Height: Minimum & Maximum
You can also limit the minimum and maximum height of an element. min-height — ensures a minimum height for an element's box. max-height — ensures a maximum height for an element's box. p { min-height: 150px; max-height: 300px; } In the example above, the height of all paragraphs will not shrink below 150 pixels and the height will not exceed 300 pixels. What will happen to the contents of an element if the max-height property is set too low for that element? It's possible that content will overflow outside of the element, resulting in content that is not legible.
Border Width 1
You can control the thickness, or width, of borders with the border-width property. The value of border-width is given in pixels. Here is an example: p { border-style: solid; border-width: 5px; } In the example above, the solid borders of all paragraphs on the page would be set to a thickness of 5 pixels. It's also possible to also set the border-width property to one of the following named thicknesses: thin medium thick While these values are perfectly valid, you may not see them often, but it's good to know that they exist.
The Alpha Value: a
You learned that RGB and hex color codes are two different methods of representing the same thing: color. However, there is one feature that RGB colors support that hex color codes do not: opacity. Opacity is a measure of how transparent a color is. To modify opacity in RGB colors, CSS offers the rgba() value. Note the slight difference in rgb() and rgba(). The extra a character in the rgba() value is known as the alpha value. It represents the opacity of a color. The alpha value can be a number between 0 or 1, inclusive. Here is an example: h1 { color: rgba(123, 88, 9, 0.5); } In the example above, the alpha value has been set to 0.5. This indicates that the color of the heading will be set to 50% of its normal opacity. Note: The alpha value can also be used for HSL colors, using hsla(): Here is an example: h1 { color: hsla(239, 45%, 22%, 0.4); }
Image vs Div Background
You've learned how to add images to a web page using the <img> element and the background property. What's the difference between these two methods? When should one method be used over another? The method used depends on the type of image. Some images are part of the content of a web page (icons, logos, album photos, etc.) and they communicate important information to a user. Other images are intended simply to style a web page (header backgrounds, etc.), not to communicate important information. When an image communicates important information, you can use the <img> element and style the image using CSS, if needed. When an image is intended to style a web page, you can use the background property and further style it with CSS.
Letter Spacing
You've learned how to increase the spacing between lines of text and words, but it's possible to get even more detailed: increasing the spacing between individual letters. The technical term for adjusting the spacing between letters is called "kerning". Kerning can be adjusted with the letter-spacing property in CSS. Here is an example: h1 { letter-spacing: 0.3em; } Like word spacing, it's not common to increase the kerning in text, but sometimes it enhances the readability of uppercase text.
Font Weight
You've probably noticed bolded text across many different web sites. It's common to bold important headings or keywords. In CSS, the font-weight property turns bold on or off. Here is an example: p { font-weight: bold; } In the example above, all paragraphs on the web page would appear bolded. The font-weight property has a second value: normal. Why does it exist? If we wanted all text on a web page to appear bolded, we could select all text elements and change their font weight to bold. If a certain section of text was required to appear normal, however, we could set the font weight of that particular element to normal, essentially "shutting off" bold for that element. In later units, you'll learn how to be more selective about what parts of your site you'd like to style.
Linking Images Too
You've probably visited websites where not all links were made up of text. Maybe the links you clicked on were images, or some other form of content. So far, we've added links that were made up of only text, like the following: <a href="https://en.wikipedia.org/wiki/Opuntia" target="_blank">Prickly Pear</a> Text-only links, however, would significantly decrease your flexibility as a web developer! Thankfully, HTML allows you to turn nearly any element into a link by wrapping that element with an anchor element. With this technique, it's possible to turn images into links by simply wrapping the <img> element with an <a> element. Here is an example: <a href="https://en.wikipedia.org/wiki/Opuntia" target="_blank"><img src="#" alt="A red prickly pear fruit"/></a> In the example above, an image of a prickly pear has been turned into a link by wrapping the outside of the <img> element with an <a> element.