KE
  • dotNet Web 3.0
  • Engineering Management
    • Process Planning (SDLC)
      • Software development process
      • Basics of SDLC models
      • Scrum
      • Kanban
      • Scrum vs Kanban: applicability
      • Scrumban
    • Estimation
      • Scope Concept
      • Estimates, Targets, and Commitments
      • Overestimate vs Underestimate
      • Decomposition and Recomposition
      • Analogy-based estimations
      • Estimating in Agile
  • Requirements
    • Software Requirements Engineering
      • Requirement definition
      • Levels of Requirements
      • Most common requirements risks
      • Characteristics of Excellent Requirements
      • Benefits from a High-Quality Requirements Process
      • Root Causes of Project Success and Failure
  • Design
    • OOD
      • Abstraction
      • Encapsulation
      • Inheritance vs Aggregation
      • Modularity
      • Polymorphism
      • Abstraction Qualities (cohesion, coupling, etc)
      • Types vs. Classes
      • Separation of concerns principle
      • SOLID
      • Design Patterns
        • Structural patterns
        • Creational patterns
        • Behavioral patterns
      • Most often used design patterns
      • Software Architecture Patterns (structure, pros & cons)
      • Inversion of Control Containers and the Dependency Injection pattern
      • Domain-Driven Design patterns
      • Anti-patterns
    • DB Design
      • Relational Terminology: Entities
      • Relational terminology: Attributes
      • Relational terminology: Records (Tuples)
      • Relationships (One-to-One, One-to-Many)
      • Understanding ER notation
      • Understanding normalization concept
      • Data Integrity
    • Modeling
      • UML: Basic Diagram Types
      • UML: Use Case Diagram (Essentials)
      • UML: Class Diagram (Essentials)
      • Entity Relationship Diagrams
      • Data Flow Diagrams
    • Security
      • Information security concepts
      • Access Control Lists (ACLs)
      • Access Control Models
      • .NET Cryptography Model
      • ASP.NET Identity
      • OWASP Top 10
      • Cross-Site Request Forgery (XSRF)
      • Protecting against cross-site scripting attacks (XSS)
      • Protecting against buffer overrun attacks
      • Protecting against SQL-injection attacks
      • CSRF/XSRF protection
    • Algorithms
      • Algorithms complexity (understanding, big O notation, complexity of common algorithms)
      • Array sorting methods (bubble sort, quick sort, merge sort)
      • Tree structure (construction, traversal)
      • Binary search algorithm
      • Hash table (creating, collisions)
      • Stack, queue, linked list (construction, understanding, usage)
  • Construction Core
    • Programming language
      • Declare namespaces, classes, interfaces, static and instance class members
      • Types casting
      • Value and reference types. Class vs Struct usage.
      • Properties and automatic properties
      • Structured Exception Handling, Exception filters
      • Collections and Generics
      • Dictionaries. Comparison of Dictionaries
      • Building enumerable types
      • Building cloneable objects
      • Building comparable types
      • Nullable types
      • Delegates, events and lambdas
      • Indexers and operator overloading
      • Anonymous types
      • Extension methods. Practices.
      • Custom Type Conversions (implicit/explicit keywords)
      • Strings and StringBuilder. String concatenation practices. String Interpolation
      • Serialization
      • System.IO namespace
      • LINQ to Objects
      • General Coding conventions for C#
      • Static Using Statement
      • Type Reflection
      • Custom attributes
      • Dispose and Finalizable patterns
      • Garbage collection
      • .Net Diagnostics
      • Implementing logging
      • Exception handling guidelines
      • Regular Expressions
      • Span<T> struct
      • C# - What's new?
      • .NET Standard overview
    • Concurrency
      • Understand differences between Concurrency vs Multi-threading vs Asynchronous
      • Concurrency: An Overview
      • Async basics
      • Task Parallelism
      • Basic Synchronization in C#
      • Deadlock problem
      • QueueBackgroundWorkItem or IHostedService for .NET Core
      • How to run Background Tasks in ASP.NET
    • Refactoring
      • Refactoring Concept (what/when/why)
      • Smells Catalog and possible re-factorings
      • Moving Features Between Objects (basic)
      • Organizing Data (basic)
      • Composing Methods (basic)
      • Simplifying Conditional Expressions (basic)
      • Making Method Calls Simpler
      • Dealing with Generalization
    • Product deploying, software installation
      • Create, configure, and publish a web package (.NET Web Profile)
      • Publishing Web Services
      • Manage packages by using NuGet, NPM and Bower
    • Networking
      • Understanding networks: layers and protocols
      • Basic understanding of TCP/IP model and protocols
      • Defining internet, intranet and VPN
      • Basics of Firewalls and DMZ
      • Application layer protocols basics (HTTP, FTP, Telnet)
      • Understanding HTTP and WWW
      • Basic troubleshooting tools (ICMP, ping, traceroute)
      • Client/Server model
      • Sockets, IP and port addressing
      • Using proxy server
      • File transfer services: FTP, TFTP
      • Name resolution services: DNS, whois
      • Remote access services: Telnet, SSH, rdesktop, VNC
      • The basic difference between HTTP and HTTPS protocols
  • Construction Web
    • Web server applications
      • ASP.NET Core
        • Application startup
        • Middleware
        • Working with Static Files
        • Routing
        • Error Handling
        • Globalization and localization
        • Configuration
        • Logging
        • File Providers
        • Dependency Injection
        • Working with Multiple Environments
        • Hosting
        • Managing Application State
        • Request Features
      • ASP.NET Core MVC
        • MVC basics (Model, View, Controller, DI)
        • Model binding and validation
        • View (Razor compilation, Layout, Tag Helpers, Partial Views, DI, View components)
        • Controllers (Route to actions, File uploads)
      • Security and Identity (concepts understanding)
        • Authentication
        • Using identity
        • Authorization with roles
      • Bundle and Minify assets
      • Develop ASP.NET Core MVC apps
      • Advanced topics for ASP.NET Core MVC
        • Application model
        • Filters
        • Areas
        • Application Parts
        • Custom Model Building
        • IActionConstraint
      • Host and deploy ASP.NET Core
      • Migrate from ASP.NET to ASP.NET Core
      • Troubleshoot ASP.NET Core projects
      • Open Web Interface for .NET (OWIN)
      • Web server implementations in ASP.NET Core
    • Web Services
      • REST
      • ASP.NET Web API
        • Routing
        • Configuration
        • Basic error handling
      • Web API-based services
      • Web API Security
      • Token based security
      • SingalR
      • Serialization Frameworks
      • Implement caching
      • gRPC on ASP.NET Core
      • API versioning
      • API documentation
    • Microservices and Cloud
      • Microservices architecture
      • Dockerize a .NET Core application
      • Development workflow for Docker apps
    • JavaScript, HTML, CSS
      • JavaScript: Variables
      • JavaScript: Data types and types conversion
      • JavaScript: Operators
      • JavaScript: Control and Loop constructions
      • JavaScript: Functions, Execution Context and Variables scopes
      • JavaScript: Arrays
      • JavaScript: JS in WebBrowser and basic DOM manipulations
      • HTML: Basic elements
      • CSS: Simple Style rules
      • CSS: selectors
      • Box model
      • HTML: Standards and Browser compatibility
      • HTML: Page Layouts with divs
      • HTML: Frames
      • CSS: Elements positioning and layering
      • CSS: Tables properties
      • CSS: Flexbox
      • Different storage
      • JavaScript: Event Understanding (propagation, capturing, attach/detach)
      • JavaScript: Closure
      • AJAX/JSON
      • Ecma script 6: OOP
      • Promise
      • Strict mode of javascript
    • JavaScript Frameworks
      • Selecting elements
      • Operating on collection
      • Manipulating with elements, working with properties, attributes and data
      • Events
      • animation and effects
      • utilities and Ajax
      • SPA (SINGLE PAGE APPLICATIONS)
      • EcmaScript 6
      • UI frameworks basics:
      • NPM basics:
      • React basics
  • Construction DB
    • SQL
      • Tables, relationships, keys, constraints understanding
      • DDL, DML, DCL understanding
      • SQL data types
      • SQL operators, functions
      • Data manipulation (insert, update, delete)
      • Retrieving data (simple select statement)
      • Joins understanding
      • Creating, modifying, removing database objects
      • Aggregations (ORDER BY, GROUP BY, HAVING, SUM, COUNT, AVG, etc)
      • Combining the results of multiple queries (UNION, EXCEPT, INTERSECT, MINUS, subqueries)
      • Sessions, transactions, locks
      • Isolation levels understanding
      • Implementing stored procedures, user-defined functions, triggers
      • Cursors
    • Data Access Layer
      • Manage connection strings and objects
      • Working with data providers
      • Connect to a data source by using a generic data access interface
      • Handle and diagnose database connection exceptions
      • Manage exceptions when selecting, modifying data
      • Build command objects and query data from data sources
      • Retrieve data source by using the DataReader
      • Manage data by using the DataAdapter and TableAdapter
      • Updating data
      • Entity Framework
        • Query data sources by using EF
        • Code First to existing DB
        • Entity Data Modeling Fundamentals
        • Querying Data
        • Data modification
  • Verification
    • Code Quality
      • MSDN: Guidelines for Names
      • SDO Best Practices Catalog - Coding Standards
      • SDO Best Practices Catalog - Code Review Process
      • SDO Best Practices Catalog - Automatic Code Inspection
      • Automated coding standards enforcement (StyleCop, Resharper)
      • Code Reviews and Toolset
      • Use Work Items (TODO, BUG etc.)
      • Preemptive Error Detection
      • Desirable characteristics of a design (minimal complexity, ease of maintenance, minimal connectednes
      • Creating high quality classes
      • Creating high quality methods
      • Guidelines for initializing variables
      • Exceptions and error handling techniques
      • Best practices of working with data types
      • Code commenting practices
    • Automated Testing (principles, patterns, and practices)
      • Software testing basic concepts
      • Software testing concept
      • Test Case
      • Test Suite
      • Test Plan
      • Testing Levels
      • Naming standards for unit tests
      • Types of test doubles (Stub, Mock, Spy, Fake, Dummy)
      • Basic coverage criteria
      • Testing concepts (Unit vs Functional vs Integration)
      • Goals of Unit Testing, What Makes a Test Valuable?
      • Styles of Unit Testing (Output / State / Collaboration)
      • Good unit test properties
      • F.I.R.S.T Principles of unit testing
      • Test Pyramid concept
      • Testing Pyramid, Agile Testing Pyramid, Diamond
      • Breaking the dependency, Interaction testing
      • Strategies for isolating the database in tests
      • Test smells and how to avoid
      • Test Organization patterns
      • Fixture setup patterns
      • Test double patterns
      • Feature-driven development (FDD)
      • Behavior-driven development (BDD)
      • Test-driven development (TDD)
      • Acceptance testing, Acceptance Test Driven Development (ATDD)
      • Continuous testing
    • Automated Testing (Frameworks, Tools, Libraries)
      • .NET unit test frameworks overview
      • .NET Mocking Frameworks, a comparison
      • xUnit
        • Primary test framework attributes
        • Asserts
        • Exception Handling in Unit Tests
        • Skipping Tests
        • Initialization and Cleanup (Assembly, Class, Test)
        • Data-driven Tests
      • NSubstitute
        • Mocking Method Calls (Using Mock Object, Return Values, Argument Matching)
        • Behavior Verification (Method Was/Not Called, a Specific Number of Times, Getter/Setter Was Called)
        • Throwing exceptions
        • Raising Events from Mock Objects
        • Returning Different Results for Sequential Calls
      • AutoFixture
      • EF Core InMemory test
      • Integration tests in ASP.NET Core
      • Isolating database data in integration tests
      • Test ASP.NET Core MVC apps
  • Configuration Management
    • Product builds and Continuous Integration
      • Automated build concept
      • Dotnet cli
      • CI/CD Basic concepts
    • Managing Versions
      • Fundamental concepts: revisions, working copy, repository, branch, baseline, trunk
      • Versioning Models
      • Distributed Version Control basics
      • Distributed systems advantages and weak sides
      • VCS Management life-cycle on (one of) major tools (clone, commit, update, revert, merge, resolve, et
      • Branching/Merging strategies
      • Blaming (annotate)
      • Revision graph/log actions (Git)
      • Integrating with Issue Tracking Systems
      • Source control Best Practices
Powered by GitBook
On this page
  • css stylesheets
  • linking a css stylesheet
  • css comments
  • setting multiple properties
  • selecting different elements
  • units of measurement
  • selecting multiple elements
  • defining fonts
  • list styles
  • reusable stylesheets
  • the cascade
  1. Construction Web
  2. JavaScript, HTML, CSS

CSS: Simple Style rules

PreviousHTML: Basic elementsNextCSS: selectors

Last updated 5 years ago

Diagram: designer’s mockup turning into CSS and raw content turning into HTML markup. Both CSS and HTML markup turn into a rendered web page

CSS provides the vocabulary to tell a web browser things like, “I want my headings to be really big and my sidebar to appear on the left of the main article.” HTML doesn’t have the terminology to make those kinds of layout decisions—all it can say is, “that’s a heading and that’s a sidebar.”

css stylesheets

CSS stylesheets reside in plaintext files with a .css extension. Create a new file called styles.css in our hello-css folder. This will house all our example snippets for this chapter.

body {
  color: #FF0000;
}

A CSS “rule” always start with a “selector” that defines which HTML elements it applies to. In this case, we’re trying to style the <body> element. After the selector, we have the “declarations block” inside of some curly braces. Any “properties” we set in here will affect the <body> element.

color is a built-in property defined by the CSS specification that determines the text color of whatever HTML elements have been selected. It accepts a hexadecimal value representing a color. #FF0000 means bright red.

linking a css stylesheet

If you try loading either of the HTML pages in a browser, you won’t see our stylesheet in action. That’s because we didn’t link them together yet. This is what the HTML <link/> element is for. In hello-css.html, change <head>to the following:

<head>
  <meta charset='UTF-8'/>
  <title>Hello, CSS</title>
  <link rel='stylesheet' href='styles.css'/>
</head>

This <link/> element is how browsers know they need to load styles.csswhen they try to render our hello-css.html page. We should now see blindingly red text everywhere:

Note that there’s no direct connection between the browser and our stylesheet. It’s only through the HTML markup that the browser can find it. CSS, images, and even JavaScript all rely on an HTML page to glue everything together, making HTML the heart of most websites.

css comments

Notice that comments in CSS are a little different than their HTML counterparts. Instead of the <!-- --> syntax, CSS ignores everything between /* and */ characters.

setting multiple properties

You can stick as many properties as you want in the declarations block of a CSS rule.

body {
  color: #414141;               /* Dark gray */
  background-color: #EEEEEE;    /* Light gray */
}

selecting different elements

Of course, you’ll want to apply styles to elements other than <body>. For that, simply add more CSS rules with different selectors. We can change the font size of our <h1> headings like so:

body {
  color: #414141;               /* Dark gray */
  background-color: #EEEEEE;    /* Light gray */
}

h1 {
  font-size: 36px;
}

And, if you want to alter h2 headings, add another rule:

h2 {
  font-size: 28px;
}

units of measurement

The em unit is very useful for defining sizes relative to some base font. In the above diagram, you can see em units scaling to match a base font size of 12px, 16px, and 20px. For a concrete example, consider the following alternative to the previous code snippet:

body {
  color: #414141;               /* Dark gray */
  background-color: #EEEEEE;    /* Light gray */
  font-size: 18px;
}

h1 {
  font-size: 2em;
}

h2 {
  font-size: 1.6em;
}

This sets our base font size for the document to 18px, then says that our <h1> elements should be twice that size and our <h2>’s should be 1.6 times bigger. If we (or the user) ever wanted to make the base font bigger or smaller, em units would allow our entire page to scale accordingly.

selecting multiple elements

h1, h2, h3, h4, h5, h6 {
  font-family: "Helvetica", "Arial", sans-serif;
}

This defines the font to use for all of our headings with a single rule. That’s great, ’cause if we ever want to change it, we only have to do so in one place. Copying and pasting code is usually a bad idea for web developers, and multiple selectors can help reduce that kind of behavior quite a bit.

defining fonts

font-family is another built-in CSS property that defines the typeface for whatever element you selected. It accepts multiple values because not all users will have the same fonts installed. With the above snippet, the browser tries to load the left-most one first (Helvetica), falls back to Arialif the user doesn’t have it, and finally chooses the system’s default sans serif font.

list styles

The list-style-type property lets you alter the bullet icon used for <li>elements. You’ll typically want to define it on the parent <ul> or <ol>element:

ul {
  list-style-type: circle;
}

ol {
  list-style-type: lower-roman;
}

reusable stylesheets

Whenever we change a style in styles.css, those changes will automatically be reflected in both of our web pages. This is how you get a consistent look and feel across an entire website.

the cascade

The CSS hierarchy for every web page looks like this:

  • The browser’s default stylesheet

  • User-defined stylesheets

  • External stylesheets (that’s us)

  • Page-specific styles (that’s also us)

  • Inline styles (that could be us, but it never should be)

This is ordered from least to most precedence, which means styles defined in each subsequent step override previous ones. For example, inline styles will always make the browser ignore its default styles. The next few sections focus on the last two options because that’s what we have control over as web developers (in addition to the external styles we’ve already been working with).

We made an effort to get you started down the right path with external stylesheets. It’s important to understand page-specific and inline styles because you’ll most definitely encounter them in the wild, but external stylesheets are by far the best place to define the appearance of your website.

page-specific styles

s an example, let’s apply some styles to our dummy.html page by updating its <head> element to this:

<head>
  <meta charset='UTF-8'/>
  <title>Dummy</title>
  <link rel='stylesheet' href='styles.css'/>
  <style>
    body {
      color: #0000FF;    /* Blue */
    }
  </style>
</head>

These apply only to dummy.html. Our hello-css.html page won’t be affected. If you did it right, you should see bright blue text when you load dummy.html in a browser.

Anything you would put in our styles.css file can live in this <style>element. It uses the exact same CSS syntax as an external stylesheet, but everything here will override rules in our styles.css file. In this case, we’re telling the browser to ignore the color property we defined for <body> in our external stylesheet and use #0000FF instead.

The problem with page-specific styles is that they’re incredibly difficult to maintain. As shown in the above diagram, when you want to apply these styles to another page, you have to copy-and-paste them into thatdocument’s <head>.

inline styles

<p>Want to try crossing out an <a href='nowhere.html'
   style='color: #990000; text-decoration: line-through;'>obsolete link</a>?
   This is your chance!</p>

Like page-specific styles, this is the same CSS syntax we’ve been working with. However, since it’s in an attribute, it needs to be condensed to a single line. Inline styles are the most specific way to define CSS. The colorand text-decoration properties we defined here trump everything. Even if we went back and added a text-decoration: none to our <style>element, it wouldn’t have any effect.

Inline styles should be avoided at all costs because they make it impossible to alter styles from an external stylesheet. If you ever wanted to re-style your website down the road, you can’t just change a few rules in your global styles.css file—you’d have to go through every single page and update every single HTML element that has a style attribute. It’s horrifying.

multiple stylesheets

CSS rules can be spread across several external stylesheets by adding multiple <link/> elements to the same page. A common use case is to separate out styles for different sections of your site. This lets you selectively apply consistent styles to distinct categories of web pages.

<!-- All product pages have this -->
<head>
  <link rel='stylesheet' href='styles.css'/>
  <link rel='stylesheet' href='product.css'/>
</head>
<!-- While all blog posts have this -->
<head>
  <link rel='stylesheet' href='styles.css'/>
  <link rel='stylesheet' href='blog.css'/>
</head>

The order of the <link/> elements matters. Stylesheets that come later will override styles in earlier ones. Typically, you’ll put your “base” or “default” styles in a global stylesheet (styles.css) and supplement them with section-specific stylesheets (product.css and blog.css). This allows you to organize CSS rules into manageable files while avoiding the perils of page-specific and inline styles.

Diagram: CSS rule composed of a selector and a series of property-value pairs
Web page with a lot of bright red text due to body selector
Diagram: HTML <link> element directing the browser to a CSS stylesheet

Many CSS properties require a unit of measurement. There’s available, but the most common ones you’ll encounter are px (pixel) and em(pronounced like the letter m).

Web page showing <h1> and<h2> headings in a different font
Diagram: Helvetica falling back to Arial falling back to any sans serif font
Diagram: Three HTML files pointing to the same global CSS stylesheet
Diagram: external stylesheets pointing to page-specific styles pointing to inline styles
Web page with all blue text due to page-specific styles overriding global CSS stylesheet
Diagram: three page-specific CSS rules attached to three individual HTML documents
Diagram: 10 CSS rules attached directly to 10 different HTML elements via inline styles
a lot of units