7. CSS Basics

A CSS rule has a selector (what to style) and a block of declarations in curly braces, each written as property: value; . Selectors can target a tag name (p), a class (.card, with a dot) or an id (#title, with a hash). You can write CSS in a style tag, in a separate .css file linked from the head, or directly on one element with the style attribute. A separate file is best, and in MVC it goes in wwwroot/css.

Key points

  • Element selector: p { } styles every paragraph.
  • Class selector: .note { } styles elements with class="note".
  • Id selector: #main-title { } styles one element.
  • When rules conflict, the more specific selector wins, then the one written last.
  • Link a file like this: <link rel="stylesheet" href="~/css/site.css" />

Example: Three kinds of selector

HTML and CSS Open in editor
<h1 id="title">CSS Selectors</h1>
<p>A normal paragraph.</p>
<p class="note">A paragraph with the note class.</p>
<p class="note">Another note.</p>

<style>
  p { color: #333; }
  .note { background: #eee; padding: 8px; }
  #title { text-decoration: underline; }
</style>
Show explanation

p styles all paragraphs, .note styles only two of them, and #title styles the single heading.

Try it yourself

Edit the code below and press Run. The result appears in the preview underneath.

Editor
Reset Preview runs in a safe sandbox. Scripts are disabled.
PREVIEW