© Lee Naylor 2016

Lee Naylor, ASP.NET MVC with Entity Framework and CSS , 10.1007/978-1-4842-2137-2_14

14. Restyling the Web Site: An Introduction

Lee Naylor

(1)Newton-le-Willows, Merseyside, UK

Over the course of the next few chapters, we’re going to introduce how to use Cascading Style Sheets (CSS), in order to change the look and feel of the web site. We are going to stick to formatting the site using plain old CSS rather than using any tools, for example SASS, which is a preprocessor that allows you to write CSS in a more object oriented manner and manages files in smaller chunks. We will also briefly introduce the frontend scripting language JavaScript in the form of the ever-popular jQuery library.

Note

To complete this chapter, you must either have completed Chapter 10 or Chapter 13, if you intend to deploy your restyled site to Azure. Alternatively, download Chapter 13’s source code from www.apress.com as a starting point.

I included this section in the book because the world of web development is evolving to something where developers need to have a more rounded skill set. In the past someone may just have been a backend developer, but there is now a developing trend of employers looking for “full-stack” developers so I’ve included CSS as an introduction to working on frontend development. The current version of CSS is known as CSS3 and you will often see CSS referred to by both these names.

Note

Throughout the examples on CSS, I keep the HTML as close as possible to its current state, therefore, at times we will use similar features to those used in the standard Bootstrap CSS, such as grid layouts. Whenever I do this, I include a detailed explanation of how the code works. The reason for doing this is so that the standard Bootstrap styles can be interchanged with the book’s stylesheets without having to recode the site. You may see that, from time to time, I add some new CSS classes, but these are specific to our CSS and do not affect the Bootstrap layout.

CSS: The Basics

We’re going to start by covering the basics of CSS, such as the composition of a style and stylesheets, followed by a brief introduction to selectors and the concept of the box model, which lies at the heart of CSS. I’ve tried to condense the very main points of CSS into a few pages to bring you up to speed quickly. I’ll expand on this section by giving more practical examples throughout the remainder of the book.

Styles

A style is a rule that tells a web browser how to format an element of a web page. You have already seen some Bootstrap styles being altered in previous chapters. A style is composed of a selector and one or more declarations. These declarations make up what is known as a declaration block and each declaration consists of a property and a value.

Consider the following style that we have updated previously in the book when correcting a Bootstrap issue:

body { padding-bottom: 20px; }

In this style, body is the selector, the declaration block is the code between the {} brackets, and padding-bottom: 20px is a declaration. Within this declaration, padding-bottom is the property and 20px is the value.

This style effectively says to the browser for the HTML body element set the padding-bottom property to 20 pixels. I’ll explain padding when we cover the box model, but this simple style basically adds a space of 20 pixels below the body element.

Stylesheets

A stylesheet is simply a collection of CSS styles. Stylesheets are either internal or external; internal stylesheets are located between opening and closing HTML <style> tags in a page’s <head> section, whereas external stylesheets are written in their own distinct files, external to the HTML of a web page. You have already seen some stylesheets during the previous chapters when making alterations to the default Bootstrap styles.

Styles can also be added outside of stylesheets to individual elements, known as inline styles. For example, in the ViewsProductsDetails.cshtml file, we’ve applied an inline style to add some padding around each image by adding a style entry as follows:

<img src="@(Url.Content(Constants.ProductThumbnailPath) + item.ProductImage.FileName)" style=padding:5px>

Despite the fact that we used this inline style for simplicity, I recommend that you avoid inline styles and stick to using stylesheets whenever you can.

Selectors

Selectors fall into two categories—those that are used to match HTML types or elements, for example p matches all paragraph <p> elements, and those used to match classes or IDs, which are assigned to HTML elements.

Throughout the book, the HTML has included CSS classes; for example, <dl class="dl-horizontal">, in which case the CSS selector .dl-horizontal is used to match it. If this HTML had been written as <dl id="dl-horizontal">, then the selector to match it would be written as #dl-horizontal.

Tip

IDs are best used sparingly if at all; it is likely to be much more efficient and productive in the long run to stick to using classes or HTML elements for styles so that they can be easily reused.

Group Selectors

To apply a style to more than one element at a time, you need to use a group selector. This is used by listing a number of selector that you want to match in a comma-separated list. For example, let’s say you wanted to match all HTML <p> elements and the dl-horizontal class to apply the same style to them. You could use a group selector such as:

p, .dl-horizontal { color : #000000 }
Tip

If you wanted to style everything, rather than listing every element, you can use the universal asterisk selector *.

Descendant Selectors

Descendant selectors match one tag within another. They can be applied to HTML tags or classes or IDs just as the group selector can be. Consider the example where we have this HTML:

<div class="news">
    <span>
        Some Text
    </span>
</div>

To style the span elements only within the news class, you can use a descendant selector, such as .news span { color : #000000 }.

You can also use the > character in between entries in a selector to find only direct descendants, e.g., div > p will find only the p tags that are direct descendants of a div tag.

Sibling Selectors

Sibling selectors are used to select elements that are next to one another. The most commonly used sibling selector is the adjacent sibling selector; for example, to select every paragraph following each <h1> tag, use the h1+p selector.

Inheritance

Inheritance refers to the way CSS applies a style that’s applied to a parent element to all its child elements. A good example of this is using the body selector to apply a standard font to everything within the body of a page. For example, if you use the body { font-family: Arial; } style, then the Arial font will be applied to everything within the body tag. You do not have to specify the same font for every element, therefore saving time.

Cascading

Cascading is the set of rules to decide which style properties get applied to an element. It is responsible for what to do when CSS properties conflict. Style conflicts can happen when the same property is inherited from multiple ancestors, and when one or more styles apply to the same element.

Styles are defined in four ways—from the browser, from internal or external stylesheets, and from inline styles. The following list shows the priority of these when it comes to deciding what wins when a style conflict occurs:

  1. Inline style

  2. Internal stylesheet

  3. External stylesheet

  4. Browser default

When it comes to determining which style wins in the same stylesheet, the general priority list is as follows:

  1. #id

  2. .class

  3. Element

In addition to this, a more specific style will override a more generic declaration. For example, the .myclass ul li style would override the style li. W3C provides the following definition of how to calculate a selector’s specificity based on four values—a, b, c, and d—where a has the highest priority and d the lowest (the higher the value of each value, the higher the priority of the style or selector):

  • To calculate a, add 1 if the style is an inline style (hence inline styles always win)

  • To calculate b, count the number of ID attributes in the selector

  • To calculate c, count the number of other classes and pseudo-classes in the selector

  • To calculate d, count the number of element names and pseudo-elements in the selector

Concatenating the four numbers a-b-c-d gives the specificity. All this sounds a bit complicated, so W3C provides the following example calculations:

*              {}  /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */
li             {}  /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */
li:first-line  {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
ul li          {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
ul ol+li       {}  /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */
h1 + *[rel=up] {}  /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
ul ol li.red   {}  /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */
li.red.level   {}  /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */
#x34y          {}  /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
style=""           /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */

There are a couple of other crucial rules well worth remembering even if you don’t remember anything else about cascading:

  • If two styles have an equal specificity, the last declared wins (i.e., the last entry in the stylesheet).

  • If you declare a style using !important then it will override any other rule (except if there is another !important rule that follows it for the same selector, in which case that will win). An example of using !important might be:

            p { font-style: italic ! important }

If you want to read more to understand how cascading works to resolve conflicts, the official documentation can be found at https://www.w3.org/TR/css3-cascade/ . Don’t worry if this all seems a bit laborious, as there are several practical examples of cascading in the following chapters.

The Box Model

CSS formatting is based around the concept of the “box model,” which in simple terms, means every element displayed in an HTML page is treated as being contained within a box. The box can have borders, margins, padding, and colors applied to it.

Borders

The border, as the name suggests, represents the edge of the box. It can be formatted to have a color, a thickness, and a style such as solid or dashed. Borders can be formatted by using the following shorthand format: border: 1px solid red;. This would create a red solid border on each side of the element that’s one pixel thick. Each border can also be formatted individually, for example using the styles:

border: 1px solid red;
border-bottom: 2px dashed blue;

This would format the bottom border differently than all the other borders. Note that in this example the order of the styles is crucial. If they were swapped, the bottom border would take the same format as all the other borders due to the cascade rule that if there are two conflicting styles of the same priority then the last entry wins.

Each border also has three individual properties—for example, border-right-width, border-right-style, and border-right-color—which can be used to override a single property for a single border.

Margins

The margins represent the space around the outside of a box. Margins can be used to increase the space between elements. A negative margin can also be used to reduce the space or overlap elements if required. Four properties control margins—margin-top, margin-right, margin-bottom, and margin-left. You can use pixels, ems, or percentages to define the size of margins such as margin-top: 5px; margin-bottom: 2em; margin-left: 20%;. This would set the top margin to five pixels, the bottom margin to twice the font size of the element, and the left margin to 20% of the element that contains the element being styled. When using percentages for margin sizes, extra care is needed to test the effect on the margins when the screen is resized.

You can also use a shorthand format to format margins; for example, margin: 0 10px 10px 20px; would format an element with a top margin of 0, a right margin of 10 pixels, a bottom margin of 10 pixels, and a left margin of 20 pixels. Use the word TRouBLe to remember the order of the shorthand format.

If you want to set all the margins to the same value, you can simply provide one value. To set the top and bottom margins the same and the left and right margins the same, you can use two values, the first being the top and bottom margin value.

Padding

Padding represents the gap between the content of the box and the border. Padding can be used to increase the size of an element. Padding and margins are sometimes confused. It is best the think of padding occurring inside the border, while margins occur outside the border. Padding styles are formatted in a similar manner to margins; for example, padding: 5px 10px 5px 10px; would create a space of five pixels between the top and bottom of the element and its contents, plus a space of 10 pixels between the right and left edges and the content.

Inline and Block Display

There are two kinds of “boxes,” inline and block, and they correspond to inline and block-level tags, respectively. A block-level tag creates a line break before and after it. Examples of the block-level tag are <div> and <p>. Inline tags run in line with surrounding content and do not have any line breaks before or after them. Examples of inline tags are <span> and <strong>. Inline and block elements behave differently when it comes to margins and padding in that you cannot increase the height of an inline element using margins or padding.

If you want to change the behavior of an element, you can do so by using the display property and setting it to block, inline, or inline-block. An example of when you may want to use this would be to change a list to display items next to one another rather than a vertical list by using display: inline;.

Using display: inline-block places an element in line with other elements but also adds margins padding to the top and bottom of the element.

Putting It Together: Visualizing the Box Model

If all this sounds a little confusing, help is at hand. Modern day browsers provide excellent support for viewing borders, padding, and margins by using the developer tools that now come bundled with each browser.

To see how all these basics mentioned so far in this chapter work, add a new HTML page in the root of the BabyStore project and name it SimpleExample.html. Now add a couple of div elements with some text and an internal stylesheet to style these as follows:

<!DOCTYPE html>
<html>
<head>
    <title></title>
        <meta charset="utf-8" />
    <style>
        body{
            color:white;
        }
        .styled {
            padding: 10px;
            margin: 20px;
            background-color: red;
            border: solid 4px black;
        }
        div{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div class="styled">
        This is some content
    </div>
    <div>This is some more content</div>
</body>
</html>

Right-click inside the file and choose View in Browser. Your browser should open and you will see a page similar to the one displayed in Figure 14-1 (the width and height may vary depending on your window size, but all the elements should appear the same).

A419071_1_En_14_Fig1_HTML.jpg
Figure 14-1. The SimpleExample page

This page is very simple but there are several things going on with it. First of all, it has an example of inheritance. Both divs have inherited their text color from the body style.

Secondly, it has an example of another cascading rule, the more specific style wins. In this case, although we included the formatting of divs after the formatted styled class, the div with the styled class assigned to it is not blue. This is because it has a specific class assigned to it and this takes precedence over the basic div style.

Finally, and most importantly, it has a simple example of the box model in action. The top div is formatted with margins, a border, and padding.

Viewing the Box Model

We’re going to use Google Chrome to view the box model of the first div element to explain how the style affects it. Google Chrome provides excellent developer support for working with CSS, hence I have chosen to use it throughout the book. To see the box model of the first div, right-click on it in Chrome and choose Inspect from the menu. This will open the Developer Tools pane of Chrome and the div will be highlighted in the HTML source code. It will also be highlighted on the page, showing that its size is actually larger than the red area. Figure 14-2 shows how this now appears.

A419071_1_En_14_Fig2_HTML.jpg
Figure 14-2. Inspecting an HTML element using Google Chrome developer tools

Rest assured that the margins, border, padding, and main content of the element are all highlighted in different colors (this can’t be seen in the print format). To view the box model of the div, click on the Computed tab in the bottom-right side of the screen. The box model should now be visible, as shown in Figure 14-3.

A419071_1_En_14_Fig3_HTML.jpg
Figure 14-3. Using the Computed tab to view the box model for the first div

You can now see exactly how the styles have affected the div. They have added a space of 20 pixels outside the border, the border is four pixels wide, and the padding has effectively “filled out” the element, adding 10 pixels of space around the text. Figure 14-4 shows a blown-up version of the box model for clarity.

A419071_1_En_14_Fig4_HTML.jpg
Figure 14-4. The box model as generated by Google Chrome for the div with the styled class applied to it

Understanding the box model is extremely powerful and useful. Without it, you are effectively flying blind when writing CSS. If you ever find yourself getting stuck and moving things around the page hoping it fits correctly, stop and go back to the basics of the box model. Use the built-in browser developer tools (usually accessed by pressing F12) to help you.

Updating the BabyStore Site to Use Your Own Stylesheet

We are now going to make practical changes to the existing BabyStore site developed in the previous chapters. Start by opening the BabyStore solution and examining the ViewsShared\_Layout.cshtml file. In this file, you will find the references to the CSS currently used by the web site, which is loaded into the site as a bundle. Bundles are used by ASP.NET to treat several related files as a single unit and optimize the delivery of item such as stylesheets and scripts. The line that loads the CSS bundle is highlighted in bold:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("∼/Content/css")
    @Scripts.Render("∼/bundles/modernizr")
</head>
<body>
...following code omitted for brevity...

The code that defines what goes into each bundle is contained in the App_StartBundleConfig.cs file. Open this file and inspect the code. Bundles are added via the RegisterBundles method. This method currently adds five bundles of two types: ScriptBundle and StyleBundle. The code that creates the stylesheet bundle is:

bundles.Add(new StyleBundle("∼/Content/css").Include(
                      "∼/Content/bootstrap.css",
                      "∼/Content/site.css"));

Next add you own new site sheet to the Content folder by right-clicking on the folder and choosing Add then Style Sheet from the popup menu. Add a new stylesheet named store.css. Next, update the styles bundle in the App_StartBundleConfig.cs file as follows:

using System.Web;
using System.Web.Optimization;


namespace BabyStore
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("∼/bundles/jquery").Include(
                        "∼/Scripts/jquery-{version}.js"));


            bundles.Add(new ScriptBundle("∼/bundles/jqueryval").Include(
                        "∼/Scripts/jquery.validate*"));


            // Use the development version of Modernizr to develop with and learn from. Then,  
                when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the
                tests you need.
            bundles.Add(new ScriptBundle("∼/bundles/modernizr").Include(
                        "∼/Scripts/modernizr-*"));


            bundles.Add(new ScriptBundle("∼/bundles/bootstrap").Include(
                      "∼/Scripts/bootstrap.js",
                      "∼/Scripts/respond.js"));


            bundles.Add(new StyleBundle("∼/Content/css").Include(
                      "∼/Content/store.css"));
        }
    }
}

Start the web site without debugging and you should now see the web site displayed with just the browser’s default formatting applied to it. Figure 14-5 shows how the site now appears in Google Chrome, with the new store.css file being used. Some of the links are purple to reflect that they have been visited.

A419071_1_En_14_Fig5_HTML.jpg
Figure 14-5. The web site using the default browser formatting

Using a CSS Reset

The aim of removing all the Bootstrap styling from the web site is to get the site to a base point where it can be restyled by adding some new custom styles. However, although all the styles have been removed, this “base point” has not yet been reached. Each web browser shows a web site without styles differently due to the fact that each browser adds its own styles to standard HTML in order to make it more readable, even though this is not an HTML standard. Each of these browser-added styles may be implemented differently from browser to browser. In order to overcome these differences, it has become popular to use something known as a CSS reset.

A CSS reset is a set of styles that attempts to reset all the browser applied styles in order to ensure you start from a level playing field no matter which browser you’re using. To create a CSS reset, add a new stylesheet to the Content folder and name it reset.css. We are not going to write a CSS reset; instead we are going to employ one of the freely available online ones. We are going to use the CSS reset available from Eric Meyer’s web site. This is available to download at http://meyerweb.com/eric/tools/css/reset/index.html .

Update the contents of the Content eset.css file with the following styles:

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/


html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
        margin: 0;
        padding: 0;
        border: 0;
        font-size: 100%;
        font: inherit;
        vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
        display: block;
}
body {
        line-height: 1;
}
ol, ul {
        list-style: none;
}
blockquote, q {
        quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
        content: '';
        content: none;
}
table {
        border-collapse: collapse;
        border-spacing: 0;
}

In basic terms, these styles set all the spacing, margin, padding, and fonts to be consistent across all browsers. Now update the StyleBundle in the App_StartBundleConfig.cs file in order to add the new reset.css file to it as follows:

bundles.Add(new StyleBundle("∼/Content/css").Include(
            "∼/Content/store.css",
            "∼/Content/reset.css"));

If you now start the web site without debugging, you will see that all the spacing has been removed and the site appears even more basic than before, as shown in Figure 14-6.

A419071_1_En_14_Fig6_HTML.jpg
Figure 14-6. The site with reset.css applied

Adding Basic Formatting

First of all, we’re going to add some basic formatting to the body tag in order to update the maximum width of the web site, add a margin, and set a default font family and a color. Update the body entry in the store.css file with the following styles:

body {
    background-color: white;
    max-width: 1024px;
    margin: 0 auto;
    font-size: 12px;
    font-family: Arial, Helvetica, sans-serif;
    color: rgb(14, 117, 204);
}

The background-color style ensures that the background of the body is always white, and then max-width specifies the maximum allowed width of the body. The margin style specifies two values—0 and auto. This is a shorthand use of the margin style and it specifies that the top and bottom margins are set to 0, while the left and right margins are set to an automatic width. This allows the left and right margins to take up any remaining available space in the browser window once the body has taken up 1024 pixels. The font-size is set to a default of 12 pixels and the font-family style is set to use three fonts where the preferred font is Arial, followed by Helvetica with the fall back font specified as sans serif. The default text color is set to blue using the color style.

At the moment, these changes only make very subtle alterations to the web site. The most visible are the changes in the text color (note this does not affect hyperlinks) and the fact that if you make the browser window wider, the margin size will change. Figure 14-7 shows the site with these new styles applied.

A419071_1_En_14_Fig7_HTML.jpg
Figure 14-7. The web site with the basic body styles applied to it. Note that the space on the left generated by setting the margin to auto. The text above the first image has also changed color

Fading In Each Page

We are now going to jump straight into a more advanced topic of CSS3, animations. With the introduction of CSS3, it became possible to add animations to your site, and many different possibilities exist. However, it’s best to use animations sparingly. We are going to use a simple animation to fade in a page every time it loads. To do this, we need to create an animation and then add a style to the element we want to apply it to.

Start by creating an animation named fadeIn, which you do by adding the following code to the store.css file:

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

This code specifies that the animation should move from opacity 0 (not visible) to opacity 1 (fully visible). Following this animation, add a new style to apply the animation to the html element; this will apply it to the whole page.

html {
    animation: fadeIn 2s;
}

If you now view the web site in Chrome, you should see that each page slowly appears into view over a two-second period.

Note

In order to keep the example simple, we are going to focus just on the latest version of Google Chrome in terms of cross-browser compatibility. This code also works in the latest versions of Microsoft Edge and Firefox. To support other versions of browsers, it is necessary to update the animation properties with vendor-specific prefixes. To cover as many browsers as possible. this code could be updated as follows for support of older versions of Internet Explorer, Chrome, Firefox, and Opera:

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}


/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}


/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}


/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}


/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}


html {
    animation: fadeIn 2s;
    -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
    -moz-animation: fadein 2s; /* Firefox < 16 */
    -ms-animation: fadein 2s; /* Internet Explorer */
    -o-animation: fadein 2s; /* Opera < 12.1 */
}

Summary

This chapter gave a basic introduction to using CSS to style a web site. It covered the basics that CSS is based on, including selectors, inheritance, and the box model. The chapter then moved on to restyling the BabyStore web site produced in earlier chapters, adding some new stylesheets to a .NET bundle and using a CSS reset to set a starting point for the restyle. We then covered how to add some basic styles to the web site and add advanced animation to fade in every page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset