CSS Part 3

Tue, Feb 20, 2018
Chapters 13-14 in Jon Duckett book. Mozilla Developer Network guide on CSS
Design a web form to look like one of the images given.


It’s important that we understand attributes which are pieces of information that can go into tags.

Image of attributes

Attributes like href="" go inside the <a> tag to specify where a user will go when they click a link.

Some common attributes

  • src — Specify the image location inside a <img /> tag.
  • alt — Specify some alternate text to describe the image in an <img /> tag.
  • href — Specify the URL an <a> tag will visit when clicked.
  • title — Specify some text that will appear when the user hovers their mouse over this tag.

There are three attributes that can go in all HTML tags that pertains to CSS:

  • id attibute — This is a unique term that gives this tag an identifier we can reference in our CSS.
  • class attribute — This is a grouping term that allows us to reference multiple tags in our CSS.
  • style attribute — This is a special way to include inline CSS, basically putting CSS code directly into an HTML tag.

Multiple Attribute Values for Classes

A single HTML tag can have have multiple distinct classes, but you must put them in the same class attribute. You just space separate them.

Multiple class attribute values

Attempting to have multiple class attributes in the same tag won’t work.

Multiple class atrributes wont work

The Box Model

The box model visualized

The CSS box model is a series of rules governing how boxes should work on the web. This includes four central properties:

  • width/height — The dimensions of the inside of a box.
  • padding — The space between the content and the box’s edges.
  • margin — The space between the box and other elements around it.
  • border — An area surrounding the box, usually visible as a line of a certain thickness.

It’s important to note that the width and height properties are counter-intuitive. They only determine the size of the area inside the box. This can be confusing when you have borders around the box, because the size of a box from border to border is determined by the width/height in addition to the padding.

Box Rules

There are a few rules governing how boxes react by default. Some of these can be counter-intuitive and really confuse people who are trying to imagine web page layout as a free-form process. It takes careful consideration of how to create designs as you conceive them in your head or from a mock-up. It’s a bit like putting together a puzzle.

  • By default a box will have a width of “auto”, or the full width of its container. This means any block-level element you create will automatically stretch the full width of the browser, or its containing element.
  • By default a box will have a height that conforms to the content of that box. So when you create a box with nothing in it, it won’t have any height. You have to set a height property in order to open the box up.
  • If you set a height in CSS, that overrides the content. This means if you set a box to be shorter than its content, the content (like text or photos) will protrude from the box.
  • By default a box will stack from the top down. If you create additional block-level elements, they stack from the top of the browser down.
    width: 100px;
    height: 100px;
    border: 1px solid black;
    overflow: visible;

The above code would produce the following:


We will cover the overflow property later.

Box Properties

Box Measurements

Let’s go over a few box properties and discuss how they work in relation to your design.

Width, Height

It’s important to remember that width and height properties only affect a specific portion of a box, the inside part between the padding.

These values can be set as px which is a static, unchanging value. Or you can use a percentage %, which is a percentage of the containing element.

Note: Using percentage values for height will only affect an element if it has a containing element. If you try to use a percentage for height on an element in the <body> element, nothing will happen (unless a height value is set on the body tag).

    height: 50%; /* won't work unless parent element has a height */

Min-width, Max-width

These properties are important when doing responsive design. They allow you to setup restrictions about how large or small an element can get. They work particularly well in conjunction with the width and height properties when they are set to percentages.

    width: 50%; /* 50% of containing element */
    max-width: 400px; /* don't go more than 400px */


The overflow property determines how to deal with content that might protrude from a box. When you manually set the width or height values of a box, there is always a chance that the text will protrude from the box (especially in responsive design). You can choose to cut off the text, have it scroll, or just show it sticking out of the box.

visible This is the default setting. The content will be visible even if it protrudes from the box.
hidden This will allow you to hide any content that doesn’t fit in the box.
scroll Allows the user to scroll any content that wouldn’t fit in the box otherwise.


The border has three distinct properties.

  • border-width Specifies the thickness of the border in pixels.
  • border-style Specifies the style of the line (i.e. solid, dashed, dotted)
  • border-color Specifies the color of the border.

You can also specify all three of these properties as a shorthand notation. This is the most common way to do this. The order is border-width border-style border-color with one or more spaces spearating the values.

    border: 1px dotted #ddffff; /* width style color */


Padding is the space between the content and the border. It can be specified as individual sides, or as a shorthand property. When done with the shorthand property, the first value refers to the top and goes clockwise. When only two values are specified, the first value refers to top and bottom, and second value to the left and right.

    padding-top: 10px;
    padding-right: 10px;
    padding-bottom: 10px;
    padding-left: 10px;
    padding: 10px 10px 10px 10px; /* shorthand, clockwise from the top */

Important note about percentages: When using percentage values for padding, they will always refer to a percentage of the width of the containing element, even when doing padding-height.

    padding-top: 30%; /* padding top will be 30% of width of containing box */


Margins work the same exact way as padding in terms of notation. There is a caveat when a bottom margin interacts with the top margin of an element below it. This effect is called collapsed margins where only the larger of the two margins will be used, and the smaller is disregarded.

Just like the padding quirk, using a percentage of margin refers to a percentage of the width of the containing element.

How to Center Elements In CSS

There are many ways to center an element in CSS depending on what you’re trying to do. Here are a few different methods.

Inline Elements

Inline elements are simple. You should just text-align them to the center. Since inline elements don’t have height properties, there is no such thing as centering something vertically.

    text-align: center;

Block Elements

To center a block element, the most standard way is to set the left-margin and right-margin to auto. This has the effect of pushing on both sides until the block element is in the center. It should note that this only works when the width of the element has a value other than the default auto.

    width: 50%; /* must have some width value */
    margin-left: auto;
    margin-right: auto;

Vertical Centering When the Height is Unknown

Sometimes you want an item centered on the page vertically when the height is unknown. There is a trick you can do that we haven’t learned just yet. The properties will be listed here, but absolute positioning will be covered in a future class.

             position : absolute;
                  top : 50%;
                 left : 50%;
    -webkit-transform : translate(-50%,-50%);
            transform : translate(-50%,-50%);

There is also a newer way to do this that doesn’t work on older version of Internet Explorer 9 and earlier. If that doesn’t matter, then you can use a new property called flexbox.

    display: flex;
    justify-content: center;
    align-items: center;

Display Property (Inline vs Block)

You can actually change an element that is natively block to inline and vice versa. The property is called display. In this method, you could actually make divs act like spans, or strong tags take up their own line.

block Elements act like boxes, taking up a whole line in the browser
inline Elements act like text and words, going side-by-side
inline-block Elements can be stacked like inline elements, but have qualities (like heights and margins) as inline elements do.
none Hide elements completely from the browser

The most common scenario is to make li elements, which are natively block elements, run as inline elements, so they are side-by-side. This is often done for making navigational menus.

    display: inline;

Hiding Elements

Another interesting value of the display property is the ability to assign it none. This essentially hides the element from the document flow completely, so that it doesn’t affect anything.

Using the visibility:hidden rule is another way to do this, but with this method the element is still a part of the document flow and will affect other elements around it (it’s just invisible).

display: none Will completely remove element as if it doesn’t exist.
visibility: hidden Just makes element invisible, but can still affect elements around it


Backgrounds can be set with colors or images. (It is generally a good idea to do both, so if the image fails to load, you still see the background color).

Here are some background properties:

background-color Sets the color of the background of an element
background-image Specify an image with notation url(img.jpg)
background-repeat Should the image repeat. Values are repeat-x repeat-y no-repeat.
background-position Where should the image be positioned? This property takes two values space separated, for the x and y position. Words like top center can be used, or percentages or pixel values (i.e. 45px 30%)
background-attachment Determines if the background image should move as the user scrolls. fixed and scroll are the two primary values
background-size Determines how large the background image should be. Using a size value of cover, contain, or a percentage 100% are all potential value. Cover means to cover the entire area, even if the image is clipped. And contain means that the entire image will show, even if there is empty space in the box.

In particular, the background-size property comes in handy, particularly when you want to place text over the background.

New Units of Measurement

There are some new units of measurement that can be done that are in relation to the viewport. So, instead of using a percentage of the containing element, you can actually use a unit of percentage based on the viewport (browser window).

  • vw — Means “viewport width” This is a percentage of the viewport’s width.
  • vh — Means “viewport height” This is a percentage of the viewport’s height.

Both values take a unit of measure that is 1/100th. So 1vw means 1% of the viewport width, and 50vw means 50% of the viewport width.

Note: You have to be careful when using viewport units of measure because as the browser window grows, content can often get too big and extend out of the viewport itself. There are also situations when scrollbars will appears due to an overflow property bug in IE. The best way to handle this is with media queries and using max-width type constrains. More info on ways to handle the bugs.

In-Class Exercise

Below is a boilerplate template we will be using in class.

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>Intro to Coding Interactives</title>
        html, body, div, span, h1, h2, h3, h4, h5, h6, p, a, em, img, strong, b, u, i, ol, ul, li, form, label, legend, caption {
            margin: 0;
            padding: 0;
            border: 0;
            outline: 0;
            font-size: 100%;
            vertical-align: baseline;
            background: transparent;

Here is some lorem (placeholder) text:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This background image file can be used in the exercise as well. This template was modified from a Themeforest one. http://demo.hammertheme.com/?theme=peek

Responsive Web

The leading philosophy in designing for mobile today is creating responsive websites. These are websites that automatically adjust their layout to adapt to various screen sizes.

Example of responsive website

The importance of responsive web is due in large by the proliferation of so many different screen sizes. Smartphones now come in many different screen sizes, as do tablets. Smart watches, and other portable devices also create more potential ways that people can see content online.

Smart phone screen sizes
Marcel Müller, CC-BY 3.0

Using Break Points for Responsive Websites

The solution to this dilemma is to use CSS Media Queries to create multiple styles for your design. The way it works is simple:

1) Start with your basic default styles. The current trend in the industry it to start with mobile first styles and work your way up. Since mobile proliferation is slated to over take desktop web usage (it already has in most industries) you should put your primary emphasis on that. 2) Decide on a series of breakpoints based on your content rather than on screen sizes. Keep the screen size agnostic to your layout. 3) Include CSS media query blocks for various viewport dimensions when the design gets too wide.


  • Create breakpoints based on content rather than devices.
  • Design small and work your way up, enhancing the design the larger it gets.
  • Lines of text should be 70 to 80 characters (roughly eight to 10 words).

CSS Media Queries

CSS Media Queries are blocks of CSS code that specify conditions when the code will be in effect. The following code means the h2 and h3 rules will only take effect if the screen size is below 800px:

@media (max-width:800px){

        font-size: 36px;
        font-size: 28px;


Remember, the max-width portion is inverse. Max means below, and Min means above (because the condition needs to be true).

You can also use queries to restrict to certain devices like screen, print, or tv. (Screen is any device with a screen, print are the styles when you print on a printer, and tv are styles with internet connected tv devices).

Beyond width and height, there are a whole host of “media features” or aspects that you can affect, such as whether or not the user is using a color monitor, or is using a specific aspect ratio.

/* printers */
@media print {


@media screen (min-aspect-ration: 1/1){


@media screen (orientation: landscape){


You can also create multiple condition using logical operators and and not.

@media screen (min-width:600px) and (max-width:800px){


@media not screen{


In the above example, only when the viewport is between 600 and 800 pixels will the styles in the code block take effect.

What takes precedence?

Just because a media query code block takes effect doesn’t mean those styles will alter the content on the page. The normal cascade rules still apply. It’s important to be specific in your media queries of the exact styles you want to alter.

Responsive Images using srcset

Newer browsers have the ability to load in different images depending on the screen size of the device you’re on. They do this by analyzing the device pixel ratio. A device pixel ratio is determined by the following formula:

num of device pixels / CSS width of an image

In order to create a series of fallbacks, you would save multiple copies of your image on the server, each with a unique name. Most people append the size to the filename. So if the full-size of your image is example.jpg, you might make a smaller copy called example-2000w.jpg, example-1600w.jpg, and finally example-750w.jpg.

In your HTML, you could include the following image tag:

<img src="example.jpg"

     srcset="example-2000w.jpg 2000w, 
             example-1600w.jpg 1600w,
             example-750w.jpg 750w"

    alt="Description of image"

This way, older browsers will only see the original src attribute and load in the full size. But newer browser—in particular, mobile browsers—will save bandwidth and time loading by loading in a smaller version that’s needed for a smaller device.

The srcset attribute requires a space after the image name, and a specification of the size of the image. Sometimes you’ll see an x dimension used. This refers to the device-pixel ratio. This is helpful, because it will help you target higher density screens (sometimes called retina screens).

Mobile Design Patterns

There are a host of websites that collect and curate mobile design patterns to get a sense of the different approaches to designing for mobile devices. Most are geared toward native applications, which tend to be more free form in their approach in web design since the designs often don’t have to adapt to larger screens.

For Mobile Websites

Awwwards pages on mobile

Mobile Awesomeness

Blue Fountain Media article on inspiring responsive design

Webdesign Inspiration

For Apps



APPreciate UI

Lovely UI

Inspired UI

Cocoa Controls (Cocoa is a reference to the coding framework many iOS apps are built with.)

Apple Human Interface Guidelines (HIG)

For years Apple has been publishing it’s own Human Interface Guidelines with tips about how to design for its various products. Their mobile interface guidelines include tips like how big to make various buttons so they can be tapped with a finger or thumb, and to ensure text doesn’t get so small that it becomes illegible.

CoDrops Tutorials

The website Tympanus has a page dedicated to UI elements and tutorials on how to build them. Most of them are highly animated, but can be useful in trying to come up with new methods of interfacing with a design.


Here is an html boilerplate template for the in-class exercise:

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>Intro to Coding Interactives</title>
    <link href='https://fonts.googleapis.com/css?family=Lato:100,400,700' rel='stylesheet' type='text/css'>
    <meta name="viewport" content="width=device-width">
        html, body, div, span, h1, h2, h3, h4, h5, h6, p, a, em, img, strong, b, u, i, ol, ul, li, form, label, legend, caption {margin: 0;padding: 0;border: 0;outline: 0;font-size: 100%;vertical-align: baseline;background: transparent;}

            font-family: Lato, sans-serif;
          background-image: url(http://newmedia.report/images/classes/intro-to-interactives/background.jpg);
          background-color: #000;
          background-size: 150%;
          background-position: left top;
          height: 70vw;
          position: relative;
          overflow: hidden;
            margin: 30px auto;
            line-height: 35px;
            font-size: 18px;
        .content p{
            margin-bottom: 20px;
            text-align: right;
            margin-right: 50%;
            margin-left: 5%;
            padding: 2% 5%;
            border-right: 8px solid white;
            box-sizing: border-box;
            border-right: 8px solid white;
            padding: 2% 5%;
            font-size: 30px;
            font-weight: 100;
            margin-right: 50%;
            color: #f7ac53;
            text-align: right;
            vertical-align: middle;
    <div class="container">
        <div class="hgroup">
          <h1>Passion Changes Everything</h1>
          <h2>Designers as Storytellers</h2>
    <div class="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam feugiat, magna ut aliquet porttitor, eros metus facilisis mauris, pretium consequat nisi lectus sit amet mauris. Nullam eget elit a elit pharetra tincidunt a ut mi. Curabitur malesuada, tortor eget interdum efficitur, tortor nulla pulvinar enim, ut blandit urna dolor et elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed erat sapien, ultrices quis congue id, mollis vulputate lacus. Nam tincidunt malesuada rhoncus. Curabitur placerat eros non nibh tempus eleifend sed tincidunt quam. In hac habitasse platea dictumst. Donec eu dignissim neque. Quisque mollis enim lectus, cursus pharetra turpis porttitor vel. Maecenas vulputate sapien quam, quis bibendum augue efficitur id. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>

        <p>Nunc et metus eget sem tempus auctor. Nam augue nisi, elementum quis tellus vitae, imperdiet blandit nulla. Curabitur hendrerit mollis lectus, et viverra ex luctus a. Vestibulum nec vehicula lorem, a venenatis quam. In ipsum lectus, pretium et dui elementum, sagittis faucibus elit. Vestibulum at quam dolor. Vestibulum faucibus, lacus ut venenatis congue, nulla leo finibus purus, id interdum quam neque eget quam. In justo arcu, ultrices eu facilisis eu, venenatis a sapien. Praesent volutpat bibendum velit vestibulum elementum.</p>

        <p>Vivamus condimentum augue eget elit sagittis, vel blandit lorem ornare. Nam dui quam, ultricies ut purus eget, semper ultrices nulla. Morbi malesuada quis erat vitae dapibus. Nulla nunc nisi, cursus in neque eu, dictum feugiat urna. Aliquam accumsan diam mauris, eu ultrices augue malesuada a. Vestibulum vel massa velit. Cras tincidunt mauris id orci porta, ut volutpat neque luctus.</p>

        <p>Nunc imperdiet tellus velit, eu cursus tortor dignissim a. Maecenas volutpat risus in libero consequat pellentesque. Cras accumsan cursus augue, in faucibus ipsum molestie vel. Vivamus hendrerit scelerisque tortor, a cursus neque accumsan eu. Quisque nec facilisis purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer a accumsan sapien. Quisque accumsan luctus nisi ac tincidunt. Duis non nunc id enim ultricies vestibulum ut non dui. Cras non libero at velit sollicitudin consequat. Mauris ac sapien facilisis justo bibendum interdum. Nunc neque ex, luctus ac velit vitae, ornare pulvinar odio. Proin dignissim urna a diam varius pulvinar. Vestibulum egestas convallis tortor non egestas. Nunc eget libero laoreet, imperdiet nisl a, accumsan nunc.</p>

        <p>Donec venenatis massa nec maximus tincidunt. Donec fermentum aliquam egestas. Maecenas auctor viverra egestas. Cras a eros at ex malesuada euismod quis non risus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin interdum ante eget turpis aliquet, quis dictum lorem efficitur. Morbi blandit nisl sit amet lacus dictum, id convallis sem vulputate. Proin sed urna at arcu venenatis finibus. Integer sollicitudin, nulla nec vehicula pellentesque, mi nulla maximus magna, in vehicula velit nisi vitae mauris. Mauris condimentum, dolor non faucibus viverra, turpis metus eleifend sem, vitae tincidunt dolor eros eget nisl. Mauris nulla leo, sodales vel aliquam eu, malesuada non nibh. Suspendisse suscipit elit in mauris dignissim, nec aliquet arcu scelerisque.</p>

Exploring the Google Web Inspector (Dev Tools)

Right now, as you read this tutorial, press Option Command i.

This will pop up a web inspector at the bottom of your screen.

Web Dev Tools Image

This box shows you the “DOM” or Document Object Model. It’s displaying the underlying live realtime HTML code for the web page, which is different than the static HTML document you’ve written.

Right click to inspect

You can also right-click an element on the page, and select “Inspect” (or “inspect element” with older browser versions) from the contextual menu to pull open the inspector.

Right-click to inspect element

Do this now on the blue boxes below:

You will notice that the boxes above, called “pills” in Bootstrap parlance, are really <li>, or list, elements inside a <ul>. And they each have an <a> tag in them.

Click and drag to re-order the elements in the DOM. You can also double-click certain regions to edit them, or you can control-click to modify/copy content.