CSS 基础

CSS (Cascading Style Sheets) is the code that styles web content. CSS 基础 walks through what you need to get started. We'll answer questions like: How do I make text red? How do I make content display at a certain location in the (webpage) layout? How do I decorate my webpage with background images and colors?

What is CSS?

Like HTML, CSS is not a programming language. It's not a markup language either. CSS is a style sheet language. CSS is what you use to selectively style HTML elements. For example, this CSS selects paragraph text, setting the color to red:

p {
  color: red;
}

					

Let's try it out! Using a text editor, paste the three lines of CSS (above) into a new file. Save the file as style.css in a directory named styles .

To make the code work, we still need to apply this CSS (above) to your HTML document. Otherwise, the styling won't change the appearance of the HTML. (If you haven't been following our project, pause here to read 处理文件 and HTML 基础 )。

  1. Open your index.html file. Paste the following line in the head (between the <head> and </head> tags):
    <link href="styles/style.css" rel="stylesheet">
    
    							
  2. 保存 index.html and load it in your browser. You should see something like this:

A mozilla logo and some paragraphs. The paragraph text has been styled red by our css. If your paragraph text is red, congratulations! Your CSS is working.

Anatomy of a CSS ruleset

Let's dissect the CSS code for red paragraph text to understand how it works :

CSS p declaration color red

The whole structure is called a ruleset . (The term ruleset is often referred to as just rule .) Note the names of the individual parts:

选择器

This is the HTML element name at the start of the ruleset. It defines the element(s) to be styled (in this example, <p> elements). To style a different element, change the selector.

声明

This is a single rule like color: red; . It specifies which of the element's properties you want to style.

特性

These are ways in which you can style an HTML element. (In this example, color 是特性在 <p> elements.) In CSS, you choose which properties you want to affect in the rule.

Property value

To the right of the property—after the colon—there is the property value . This chooses one out of many possible appearances for a given property. (For example, there are many color values in addition to red )。

Note the other important parts of the syntax:

  • Apart from the selector, each ruleset must be wrapped in curly braces. ( {} )
  • Within each declaration, you must use a colon ( : ) to separate the property from its value or values.
  • Within each ruleset, you must use a semicolon ( ; ) to separate each declaration from the next one.

To modify multiple property values in one ruleset, write them separated by semicolons, like this:

p {
  color: red;
  width: 500px;
  border: 1px solid black;
}

					

Selecting multiple elements

You can also select multiple elements and apply a single ruleset to all of them. Separate multiple selectors by commas. For example:

p, li, h1 {
  color: red;
}

					

Different types of selectors

There are many different types of selectors. The examples above use element selectors , which select all elements of a given type. But we can make more specific selections as well. Here are some of the more common types of selectors:

Selector name What does it select 范例
Element selector (sometimes called a tag or type selector) All HTML elements of the specified type. p
selects <p>
ID selector The element on the page with the specified ID. On a given HTML page, each id value should be unique. #my-id
selects <p id="my-id"> or <a id="my-id">
Class selector The element(s) on the page with the specified class. Multiple instances of the same class can appear on a page. .my-class
selects <p class="my-class"> and <a class="my-class">
Attribute selector The element(s) on the page with the specified attribute. img[src]
selects <img src="myimage.png"> 而非 <img>
Pseudo-class selector The specified element(s), but only when in the specified state. (For example, when a cursor hovers over a link.) a:hover
selects <a> , but only when the mouse pointer is hovering over the link.

There are many more selectors to discover. To learn more, see the MDN Selectors guide .

Fonts and text

Now that we've explored some CSS fundamentals, let's improve the appearance of the example by adding more rules and information to the style.css 文件。

  1. First, find the output from Google Fonts that you previously saved from What will your website look like? . Add the <link> element somewhere inside your index.html 's head (anywhere between the <head> and </head> tags). It looks something like this:
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    
    							
    This code links your page to a style sheet that loads the Open Sans font family with your webpage.
  2. Next, delete the existing rule you have in your style.css file. It was a good test, but let's not continue with lots of red text.
  3. Add the following lines (shown below), replacing the font-family assignment with your font-family selection from What will your website look like? . The property font-family refers to the font(s) you want to use for text. This rule defines a global base font and font size for the whole page. Since <html> is the parent element of the whole page, all elements inside it inherit the same font-size and font-family .
    html {
      font-size: 10px; /* px means "pixels": the base font size is now 10 pixels high  */
      font-family: "Open Sans", sans-serif; /* this should be the rest of the output you got from Google fonts */
    }
    
    							

    注意: Anything in CSS between /* and */ CSS comment . The browser ignores comments as it renders the code. CSS comments are a way for you to write helpful notes about your code or logic.

  4. Now let's set font sizes for elements that will have text inside the HTML body ( <h1> , <li> ,和 <p> ). We'll also center the heading. Finally, let's expand the second ruleset (below) with settings for line height and letter spacing to make body content more readable.
    h1 {
      font-size: 60px;
      text-align: center;
    }
    p, li {
      font-size: 16px;
      line-height: 2;
      letter-spacing: 1px;
    }
    
    							

Adjust the px values as you like. Your work-in-progress should look similar to this:

a mozilla logo and some paragraphs. a sans-serif font has been set, the font sizes, line height and letter spacing are adjusted, and the main page heading has been centered

CSS: all about boxes

Something you'll notice about writing CSS: a lot of it is about boxes. This includes setting size, color, and position. Most HTML elements on your page can be thought of as boxes sitting on top of other boxes.

a big stack of boxes or crates sat on top of one another

Photo from https://www.geograph.org.uk/photo/3418115 Copyright © Jim Barton cc-by-sa/2.0

CSS layout is mostly based on the box model. Each box taking up space on your page has properties like:

  • padding , the space around the content. In the example below, it is the space around the paragraph text.
  • border , the solid line that is just outside the padding.
  • margin , the space around the outside of the border.

three boxes sat inside one another. From outside to in they are labelled margin, border and padding

In this section we also use:

  • width (of an element).
  • background-color , the color behind an element's content and padding.
  • color , the color of an element's content (usually text).
  • text-shadow sets a drop shadow on the text inside an element.
  • display sets the display mode of an element. (keep reading to learn more)

To continue, let's add more CSS. Keep adding these new rules at the bottom of style.css . Experiment with changing values to see what happens.

Changing the page color

html {

background-color


:

 #00539F

;


}


					

This rule sets a background color for the entire page. Change the color code to the color you chose in What will my website look like? .

Styling the body

body {
  width: 600px;
  margin: 0 auto;
  background-color: #FF9500;
  padding: 0 20px 20px 20px;
  border: 5px solid black;
}

					

There are several declarations for the <body>  element. Let's go through these line-by-line:

  • width: 600px; This forces the body to always be 600 pixels wide.
  • margin: 0 auto; When you set two values on a property like margin or padding , the first value affects the element's top and bottom side (setting it to 0 in this case); the second value affects the left and right side. (Here, auto is a special value that divides the available horizontal space evenly between left and right). You can also use one, two, three, or four values, as documented in Margin Syntax .
  • background-color: #FF9500; This sets the element's background color. This project uses a reddish orange for the body background color, as opposed to dark blue for the <html> element. (Feel free to experiment.)
  • padding: 0 20px 20px 20px; This sets four values for padding. The goal is to put some space around the content. In this example, there is no padding on the top of the body, and 20 pixels on the right, bottom and left. The values set top, right, bottom, left, in that order. As with margin , you can use one, two, three, or four values, as documented in Padding Syntax .
  • border: 5px solid black; This sets values for the width, style and color of the border. In this case, it's a five-pixel–wide, solid black border, on all sides of the body.

Positioning and styling the main page title

h1 {
  margin: 0;
  padding: 20px 0;
  color: #00539F;
  text-shadow: 3px 3px 1px black;
}

					

You may have noticed there's a horrible gap at the top of the body. That happens because browsers apply default styling to the <h1> element (among others). That might seem like a bad idea, but the intent is to provide basic readability for unstyled pages. To eliminate the gap, we overwrite the browser's default styling with the setting margin: 0; .

Next, we set the heading's top and bottom padding to 20 pixels.

Following that, we set the heading text to be the same color as the HTML background color.

最后, text-shadow applies a shadow to the text content of the element. Its four values are:

  • The first pixel value sets the horizontal offset of the shadow from the text: how far it moves across.
  • The second pixel value sets the vertical offset of the shadow from the text: how far it moves down.
  • The third pixel value sets the blur radius of the shadow. A larger value produces a more fuzzy-looking shadow.
  • The fourth value sets the base color of the shadow.

Try experimenting with different values to see how it changes the appearance.

Centering the image

img {
  display: block;
  margin: 0 auto;
}

					

Next, we center the image to make it look better. We could use the margin: 0 auto trick again as we did for the body. But there are differences that require an additional setting to make the CSS work.

<body> block element, meaning it takes up space on the page. The margin applied to a block element will be respected by other elements on the page. In contrast, images are inline elements, for the auto margin trick to work on this image, we must give it block-level behavior using display: block; .

注意: The instructions above assume that you're using an image smaller than the width set on the body. (600 pixels) If your image is larger, it will overflow the body, spilling into the rest of the page. To fix this, you can either: 1) reduce the image width using a graphics editor , or 2) use CSS to size the image by setting the width property on the <img> element with a smaller value.

注意: Don't be too concerned if you don't completely understand display: block; or the differences between a block element and an inline element. It will make more sense as you continue your study of CSS. You can find more information about different display values on MDN's display reference page .

结论

If you followed all the instructions in this article, you should have a page that looks similar to this one:

a mozilla logo, centered, and a header and paragraphs. It now looks nicely styled, with a blue background for the whole page and orange background for the centered main content strip.

(You can view our version here .) If you get stuck, you can always compare your work with our finished example code on GitHub .

In this exercise, we have just scratched the surface of CSS. To go further, see Learning to style HTML using CSS .

In this module

发现此页面有问题吗?

最后修改: , 由 MDN 贡献者

  1. Complete beginners start here!
  2. Web 快速入门
    1. Getting started with the Web overview
    2. 安装基本软件
    3. What will your website look like?
    4. 处理文件
    5. HTML 基础
    6. CSS 基础
    7. JavaScript 基础
    8. 发布您的网站
    9. How the Web works
  3. HTML — Structuring the Web
  4. HTML 介绍
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. 多媒体和嵌入
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML 表格
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. CSS 第一步
    1. CSS first steps overview
    2. What is CSS?
    3. Getting started with CSS
    4. How CSS is structured
    5. How CSS works
    6. Using your new knowledge
  9. CSS 构建块
    1. CSS building blocks overview
    2. Cascade and inheritance
    3. CSS 选择器
    4. The box model
    5. Backgrounds and borders
    6. Handling different text directions
    7. Overflowing content
    8. Values and units
    9. Sizing items in CSS
    10. Images, media, and form elements
    11. Styling tables
    12. Debugging CSS
    13. Organizing your CSS
  10. 样式化文本
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  11. CSS 布局
    1. CSS layout overview
    2. Introduction to CSS layout
    3. Normal Flow
    4. Flexbox
    5. Grids
    6. Floats
    7. 位置
    8. Multiple-column Layout
    9. Responsive design
    10. Beginner's guide to media queries
    11. Legacy Layout Methods
    12. Supporting Older Browsers
    13. Fundamental Layout Comprehension
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript 第一步
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic math in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. 数组
    10. Assessment: Silly story generator
  14. JavaScript 构建块
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. 事件介绍
    8. Assessment: Image gallery
  15. 引入 JavaScript 对象
    1. Introducing JavaScript objects overview
    2. Object basics
    3. 对象原型
    4. Object-oriented programming concepts
    5. Classes in JavaScript
    6. Working with JSON data
    7. Object building practice
    8. Assessment: Adding features to our bouncing balls demo
  16. 异步 JavaScript
    1. Asynchronous JavaScript overview
    2. General asynchronous programming concepts
    3. Introducing asynchronous JavaScript
    4. Cooperative asynchronous Java​Script: Timeouts and intervals
    5. Graceful asynchronous programming with Promises
    6. Making asynchronous programming easier with async and await
    7. Choosing the right approach
  17. 客户端侧 Web API
    1. 客户端侧 Web API
    2. Introduction to web APIs
    3. Manipulating documents
    4. Fetching data from the server
    5. Third party APIs
    6. Drawing graphics
    7. Video and audio APIs
    8. Client-side storage
  18. Web forms — Working with user data
  19. Core forms learning pathway
    1. Web forms overview
    2. Your first form
    3. How to structure a web form
    4. Basic native form controls
    5. The HTML5 input types
    6. Other form controls
    7. Styling web forms
    8. Advanced form styling
    9. UI pseudo-classes
    10. Client-side form validation
    11. Sending form data
  20. Advanced forms articles
    1. How to build custom form controls
    2. Sending forms through JavaScript
    3. CSS property compatibility table for form controls
  21. Accessibility — Make the web usable by everyone
  22. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  23. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  24. Tools and testing
  25. Client-side web development tools
    1. Client-side web development tools index
    2. Client-side tooling overview
    3. Command line crash course
    4. Package management basics
    5. Introducing a complete toolchain
    6. Deploying our app
  26. Introduction to client-side frameworks
    1. Client-side frameworks overview
    2. Framework main features
  27. React
    1. Getting started with React
    2. Beginning our React todo list
    3. Componentizing our React app
    4. React interactivity: Events and state
    5. React interactivity: Editing, filtering, conditional rendering
    6. Accessibility in React
    7. React resources
  28. Ember
    1. Getting started with Ember
    2. Ember app structure and componentization
    3. Ember interactivity: Events, classes and state
    4. Ember Interactivity: Footer functionality, conditional rendering
    5. Routing in Ember
    6. Ember resources and troubleshooting
  29. Vue
    1. Getting started with Vue
    2. Creating our first Vue component
    3. Rendering a list of Vue components
    4. Adding a new todo form: Vue events, methods, and models
    5. Styling Vue components with CSS
    6. Using Vue computed properties
    7. Vue conditional rendering: editing existing todos
    8. Focus management with Vue refs
    9. Vue resources
  30. Svelte
    1. Getting started with Svelte
    2. Starting our Svelte Todo list app
    3. Dynamic behavior in Svelte: working with variables and props
    4. Componentizing our Svelte app
    5. Advanced Svelte: Reactivity, lifecycle, accessibility
    6. Working with Svelte stores
    7. TypeScript support in Svelte
    8. Deployment and next steps
  31. Angular
    1. Getting started with Angular
    2. Beginning our Angular todo list app
    3. Styling our Angular app
    4. Creating an item component
    5. Filtering our to-do items
    6. Building Angular applications and further resources
  32. Git and GitHub
    1. Git and GitHub overview
    2. Hello World
    3. Git Handbook
    4. Forking Projects
    5. About pull requests
    6. Mastering Issues
  33. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  34. Server-side website programming
  35. 第一步
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  36. Django Web 框架 (Python)
    1. Django web framework (Python) overview
    2. 介绍
    3. 设置开发环境
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  37. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  38. Further resources
  39. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. Web mechanics
    5. Tools and setup
    6. Design and accessibility