CSS - MuxiaoWFSkip to main content
This page was machine-translated and may contain errors or omissions. / 本页面为机器翻译,可能存在错漏。
CSS

CSS

Tue Jun 28 2005
4679 words · 45 minutes

CSS

style Basics

Selectors

A CSS file is essentially defined using the form element { property: value; }. You can also define styles with #id { property: value; } or .class { property: value; }.

h1 {
/* center the text */
text-align: center;
}
body {
/* background color */
background-color: blue;
}
#menu {
/* width of the element with id="menu" */
width: 300px;
/* alternatively: width: 80%; */
/* the two lines below are equivalent to centering */
margin-left: auto;
margin-right: auto;
}
.cls {
/* width of the element with class="cls" */
width: 300px;
}

When multiple objects need the same configuration, you can use object1, object2 { property: value; }. To select everything, use *{ style }.

For an element’s class, you can define it with element.class { style }.

Combinator Selectors

.cls p {
/* set values for all <p> elements inside class="cls" */
display: inline-block;
}
  1. Descendant selector (space separated) .class element { property: value; }
  2. Child selector (> separated) .class>element { property: value; } — sets values for the direct (first-level) child <p> elements of class=“cls”
  3. Adjacent sibling selector (+ separated) .class+element { property: value; } — sets values for the element <p> that shares the same parent as class=“cls” and is the immediately following one
  4. General sibling selector (~ separated) .class~element { property: value; } — sets values for all <p> elements after class=“cls” that share the same parent

Attribute Selectors

Used to select HTML elements based on their attributes or attribute values: [type] { property: value; } selects all elements that have the type attribute (note: it’s the attribute). For example:

/* set all elements that have a title attribute to blue */
<style>
[title] {
color: blue;
}
</style>
<h1 title="Hello world">Hello world</h1>

Additional usages:

  • [attribute="value"] selects elements whose specified attribute matches the value exactly.
  • [attribute~="value"] selects elements whose attribute value contains the specified word (one of a space-separated list of words).
  • [attribute*="value"] selects elements whose attribute value contains the specified substring.
  • [attribute|="value"] selects elements whose attribute value starts with the specified value followed immediately by a hyphen - (commonly used for languages).
  • [attribute^="value"] selects elements whose attribute value starts with the specified value.
  • [attribute$="value"] selects elements whose attribute value ends with the specified value.

Background

The background parameters are: background-color, background-image, background-repeat, background-attachment, background-position — which control color, image, whether to repeat, whether to stay fixed, and the starting position respectively. In that order they can also be abbreviated into a single background property, e.g.:

body {
background-image: url('https://example.com/images/myImg.jpg');
background-repeat: no-repeat;
/* the background image appears only once, otherwise multiple copies repeat until the area is filled */
background-position: right top;
/* the background image is in the top-right corner of the browser window */
background-attachment: fixed;
/* the background image is fixed and does not scroll with the page */
}
/* equivalent to the above */
body {
background: url('https://example.com/images/myImg.jpg') no-repeat fixed right top;
}

Example: a background that repeats, does not scroll with the page (relatively static), and starts in the top-right corner


Gradients

In background-image settings you can use a gradient gradient, which comes in two kinds: linear gradient linear-gradient and radial gradient radial-gradient (circular spread).

Example: linear syntax: background-image: linear-gradient(direction, color-stop1, color-stop2, ...); where direction specifies the gradient direction. Optional values include to top, to right, to bottom right, meaning bottom-to-top, left-to-right, and top-left-to-bottom-right respectively.

<style>
#gradient1 {
background-image: linear-gradient(#92ff11, #48e8ef);
}
</style>
<div id="gradient1"></div>

Radial syntax: background-image: radial-gradient(center, shape size, start-color, ..., last-color);

<style>
#gradient2 {
background-image: radial-gradient(#92ff11, #48e8ef);
}
</style>
<div id="gradient2"></div>

Text Styles

  • color: text color
  • font-family: font
  • text-align: text alignment. Optional values are left, right, center, justify, meaning left-aligned, right-aligned, centered, and justified respectively.
  • font-size: font size
  • font-weight: font weight. Optional values are normal, bold, bolder, lighter, meaning normal, bold, bolder, and lighter respectively.
  • font-style: font style. Optional values are normal, italic, oblique, meaning normal, italic, and oblique respectively.
  • text-decoration: text decoration. Optional values are none, underline, overline, line-through, meaning no decoration, underline, overline, and strikethrough respectively.
  • text-indent: text indentation

Opacity

The opacity property: transparency, ranging from 0 to 1, where 0 is fully transparent and 1 is fully opaque.

Tip: use :hover to change the opacity on mouse hover.

For the <a> type / pseudo-classes (see below):

  1. a:link — normal, unvisited link
  2. a:visited — a link the user has already visited
  3. a:hover — when the user’s mouse is over the link
  4. a:active — the moment the link is clicked

Selectable parameters include color, text-decoration, background-color, representing text color, whether there is an underline, and background color respectively. Example:

/* text color for all hyperlinks */
a {
color: black;
}
/* text color after being clicked */
a:visited {
color: grey;
}
/* color on mouse hover */
a:hover {
color: brown;
}

Example:

css


Box Model

The CSS box model is essentially a box that wraps around HTML elements. It includes: margin, border, padding, and the actual content. Example below:

.box {
/* actual content is 300px wide and tall */
width: 300px;
height: 300px;
/* margin is 50px */
margin: 50px;
/* border is a 10px green part */
border: 10px solid green;
/* padding is 10px, same as the background color */
padding: 10px;
background-color: yellow;
}

Example: a box whose actual content (blue) is 300px wide and tall, margin (transparent, the distance from the page) is 50px, border (green) is 10px, and padding (yellow) is 10px:

That is, the entire element occupies 300 + 50*2 (left and right margins) + 10*2 (border) + 10*2 (padding) = 500 pixels.

Horizontal / Vertical Alignment

Use margin: auto to center horizontally; note: a width must be set for it to take effect, otherwise it fills the full page width.

For text, use text-align: center to center it.

Example:

a centered box & text

You can also use float and position: absolute for horizontal centering.

For vertical centering, simply use padding: top/bottom left/right — setting one value represents the top/bottom spacing:

.center2 {
width: 300px;
padding: 20px 0;
}

Example:

vertical centering

position: absolute works the same way.

Border

The border-style property specifies the type of border to display. Optional values:

  • none: no border
  • dotted: dotted border
  • dashed: dashed border
  • solid: solid border
  • double: double border
  • groove: 3D grooved border. Effect depends on the border-color value.
  • ridge: 3D ridged border. Effect depends on the border-color value.
  • inset: 3D inset border. Effect depends on the border-color value.
  • outset: 3D outset border. Effect depends on the border-color value.
  • hidden: hidden border
  • mixed border: a mixed border allows specifying multiple border types, e.g. border-style: dotted dashed solid double; means top dotted, right dashed, bottom solid, left double, equivalent to border-top-style: dotted; border-right-style: solid; border-bottom-style: dotted; border-left-style: solid;

You can also set the border width via border-width, the border color via border-color, and the border corner radius via border-radius.

You can also set border-top-width and border-top-color like in the mixed border example above via border-top-style: dotted;.


Example:

no border.

dotted border.

dashed border.

solid border.

double border.

grooved border.

ridged border.

inset border.

outset border.

mixed border


Display

The display and visibility properties specify how an element is displayed.

  • display property:

  • display: none: hides the element; the element won’t be shown, but the element itself still exists and still occupies space.

  • display: block: the element is displayed as a block-level element, occupying its own line and filling the parent element.

  • display: inline: the element is displayed as an inline element, not occupying its own line, and fills the parent element.

  • visibility property:

  • visibility: hidden: hides the element; the element won’t be shown, but the element itself still exists and still occupies space.

  • visibility: visible: shows the element; the element is displayed and occupies space.

  • visibility: collapse: hides the element; the element won’t be shown, but the element itself still exists and does NOT occupy space.

Forms

As we all know, HTML forms are built on input. In CSS, use input[type=type] (attribute selector) to match input elements of a specified type.

It is recommended to set the border border, padding padding, focus :focus, hover :hover, and required :required (the same applies to other form elements).

For text areas, it is recommended to set resize: none to remove the bottom-right drag-to-resize handle.


Button

Straight to the example:

<style>
.my-button {
background-color: antiquewhite;
position: relative;
font-size: 14px;
padding: 10px;
width: 100px;
text-align: center;
/* remove the extra pseudo-element */
overflow: hidden;
}
/* pseudo-element (a white cloth slightly larger than the button) */
.my-button:after {
content: "";
background: #dadada;
display: block;
position: absolute;
/* slightly larger to fully cover the entire button */
padding-top: 120%;
padding-left: 120%;
margin-left: -10px;
margin-top: -100%;
/* initial opacity is 0 */
opacity: 0;
transition: all 0.4s
}
/* after the button is pressed */
.my-button:active:after {
/* shrink the pseudo-element to button size (gives it a transition animation) */
padding: 0;
margin: 0;
/* opacity becomes 1, making the pseudo-element instantly visible */
opacity: 1;
transition: 0s
}
/* text inside the button */
.my-button span {
display: inline-block;
position: relative;
transition: 0.4s;
}
/* pseudo-element of the inner text */
.my-button span:after {
content: '»';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.2s;
}
/* when the mouse moves over it, the inner text shifts a bit */
.my-button:hover span {
padding-right: 10px;
}
/* when the mouse moves over it, the pseudo-element of the inner text shows */
.my-button:hover span:after {
opacity: 1;
right: 0;
}
</style>
<button class="my-button"><span>button</span></button>

Result:

Overflow

Values:

  • visible (default). Content is not clipped and is rendered outside the element’s box.
  • hidden — content is clipped and the rest is invisible.
  • scroll — content is clipped, but the browser shows a scrollbar to view the rest.
  • auto — if content is clipped, the browser shows a scrollbar to view the rest.
  • inherit — specifies that the overflow value should be inherited from the parent element.
.overflow {
/* define a scrollable element */
overflow: scroll;
height: 100px;
}

Example: - auto

1

2

3


Layout

Positioning position

The position property specifies the type of positioning for an element. Optional values:

  • static (default), normal document flow
  • absolute — absolute positioning, positioned relative to the nearest positioned ancestor element (non-static); if none, positioned relative to the browser window. The element is completely removed from the document flow and does not occupy its original space; other elements ignore its existence.
  • relative — relative positioning, positioned relative to its normal position (static). The element remains in the document flow, occupying its original space, only visually offset.
  • fixed — fixed positioning, positioned relative to the browser window (scroll position unchanged).
  • inherit — inherits from the parent element.
<style>
.container {
/* ancestor element is non-static */
position: relative;
width: 300px;
height: 300px;
border: 1px solid black;
}
.box {
width: 100px;
height: 100px;
background-color: #f5f5f5;
border: 1px solid #ccc;
}
</style>
<div class="container">
<div class="box" style="position: relative; top: 20px; left: 20px;">Relative</div>
<div class="box" style="position: absolute; top: 60px; left: 60px;">Absolute</div>
</div>
Relative
Absolute

Multi-column

The column-count property specifies how many columns an element should be divided into (default is 1 column); the column-gap property specifies the gap between columns; the column-rule property specifies the dividing line between columns.

<style>
.multi-col-container {
column-count: 3; /* define three columns */
column-gap: 20px; /* column spacing */
column-rule: 1px solid #ccc; /* column dividing line */
}
</style>
<div class="multi-col-container">
<p>
This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout.
</p>
</div>

This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout. This is Twilight Maple's monkey den. What's being demonstrated now is the multi-column layout.

Float / Clear

Floats above the element.

clear specifies that no floating elements are allowed around the element. float specifies whether a box (element) can float.

Optional values: left — left side right — right side none — no float inherit — inherit


Example: the first “this” character will float to the left of the page, regardless of page size

This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.


Flexbox

Apply display: flex to the parent container so that child elements automatically adjust their width or height based on the container size.

Typically used when you need to control a single row / column

<style>
/* Example: equal-height card layout (cross-axis stretch + dynamic wrapping) */
.card-container {
display: flex;
flex-wrap: wrap; /* allow wrapping */
gap: 1rem;
padding: 2rem;
}
.card {
flex: 1; /* dynamically fill remaining space */
min-width: 150px; /* minimum width constraint to ensure readability */
background: #f5f5f5;
padding: 1.5rem;
border-radius: 8px;
}
/* Example: vertical centering */
.centered-section {
display: flex;
min-height: 300px; /* needs a height to vertical-center */
background: #e0e0e0;
}
.centered-content {
margin: auto; /* horizontal and vertical centering */
text-align: center;
}
</style>
<!-- Example: card layout -->
<div class="card-container">
<div class="card">
<h3>Card 1</h3>
<p>Dynamic-width card; different content heights but equal container height</p>
</div>
<div class="card">
<h3>Card 2</h3>
<p>Achieves equal width via flex:1, auto-wraps to respond to screen size</p>
<p>Extra paragraph to show the height difference</p>
</div>
<div class="card">
<h3>Card 3</h3>
<p>Minimum width constraint ensures readability</p>
</div>
</div>
<!-- Example: vertical centering -->
<section class="centered-section">
<div class="centered-content">
<h2>Centered</h2>
<p>Centered without computing margins</p>
</div>
</section>

Card 1

Dynamic-width card; different content heights but equal container height

Card 2

Achieves equal width via flex:1, auto-wraps to respond to screen size

Extra paragraph to show the height difference

Card 3

Minimum width constraint ensures readability

Centered

Centered without computing margins

More applications can be seen in the navigation bar in the final usage examples

Grid Layout

Define a container and set display: grid, then explicitly define rows and columns via grid-template-columns and grid-template-rows.

In use, grid-column: start / end and grid-row: start / end specify an element’s position in the grid. Here start is the starting row/column and end is the ending row/column (exclusive).

Typically used when you need to control both rows and columns at the same time

<style>
.dashboard {
display: grid;
grid-template-columns: repeat(3, 1fr); /* define three columns, each equal width */
grid-template-rows: repeat(2, 100px) 200px; /* define three rows: first two are 100px, last is 200px */
gap: 10px; /* grid gap */
width: 100%;
max-width: 900px;
background-color: #fff;
padding: 10px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.item {
background-color: #e0e0e0;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.2em;
color: #333;
border-radius: 4px;
}
/* adjust a specific module's size and position */
.item-1 {
grid-column: 1 / 3; /* span from column 1 to column 2 (excluding column 3) */
grid-row: 1 / 2; /* occupy row 1 */
background-color: #ffcccb;
}
.item-2 {
grid-column: 3 / 4;
grid-row: 1 / 3; /* span from row 1 to row 2 */
background-color: #d4edda;
}
.item-3 {
grid-column: 1 / 2;
grid-row: 2 / 3;
background-color: #d1ecf1;
}
.item-4 {
grid-column: 2 / 3;
grid-row: 2 / 3;
background-color: #fff3cd;
}
.item-5 {
grid-column: 3 / 4;
grid-row: 3 / 4;
background-color: #d4edda;
}
.item-6 {
grid-column: 1 / 4; /* span all columns */
grid-row: 3 / 4;
background-color: #f8d7da;
}
</style>
<div class="dashboard">
<div class="item item-1">Item 1</div>
<div class="item item-2">Item 2</div>
<div class="item item-3">Item 3</div>
<div class="item item-4">Item 4</div>
<div class="item item-5">Item 5</div>
<div class="item item-6">Item 6</div>
</div>
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6

Animation

Define an animation with @keyframes and apply it to an element.

<style>
.flash-div {
width: 100px;
height: 100px;
background: red;
/* use the animation, infinite loop playback */
animation: flash 5s infinite;
}
/* define the animation */
@keyframes flash {
0% {
background: red;
}
50% {
background: yellow;
}
100% {
background: red;
}
}
</style>
<div class="flash-div"></div>

Example: - looping animation

Transition

The transition property specifies the transition effect for an element, including:

  • transition-property — the name of the CSS property to which the transition applies
  • transition-duration — the time the transition effect takes. Default is 0.
  • transition-timing-function — the timing curve of the transition effect. Default is “ease”.
  • transition-delay — when the transition effect starts. Default is 0.
<style>
.transition {
width: 100px;
height: 100px;
background: red;
/* define a transition that, after a 1s delay, changes the width over 1s with a linear timing function */
transition: width 1s linear 1s;
}
.transition:hover {
width: 200px;
}
</style>
<div class="transition"></div>

Example: a transition that, after a 1s delay, changes the width over 1s with a linear timing function

Media Queries

Media queries include:

  • the width and height of the viewport
  • the width and height of the device, and orientation (landscape, portrait)
  • resolution

The syntax is:

@media not|only media-type and (restrictions) {
CSS code
}

For example:

<style>
.my-media {
width: 100px;
height: 100px;
background-color: antiquewhite;
}
/* applied when the screen width is less than or equal to 1000px */
@media screen and (max-width: 1000px) {
.my-media {
width: 100px;
height: 100px;
background-color: black;
}
}
</style>
<div class="my-media"></div>

Result: (resize the browser width to see the effect)

Pseudo-classes

We already saw some pseudo-classes in the hyperlink example above: :hover, :active, :focus, :visited, :link. Here are some others:

:first-child

p:first-child i {
/* match all <i> elements inside the <p> element that is the first child of its parent */
color: blue;
}

Similarly, there is :last-child (last child), :nth-child (second child), :nth-last-child (second-to-last child).

For more pseudo-classes, see w3school pseudo-classes on your own.

Pseudo-elements

after

The ::after pseudo-element adds content after an element, for example:

p::after {
content: " - tail";
color: red;
}

Example:

this is the actual content


Other pseudo-elements don’t seem very useful either; check w3school pseudo-elements on your own.

Practical Usage

A navigation box easily brings to mind an unordered list + links, but this needs CSS to assist.

<style>
ul {
/* remove the list bullet marker */
list-style-type: none;
/* remove the list's inner and outer margins */
margin: 0;
padding: 0;
/* set width to 25% of the page */
width: 25%;
background-color: #f1f1f1;
/* set the list to fixed positioning */
position: fixed;
/* overflow the element box; show a scrollbar if overflowing */
overflow: auto;
}
li a {
/* block-level, each element on its own line */
display: block;
color: #000;
padding: 8px 16px;
/* remove text decoration (underline) */
text-decoration: none;
}
li a:active {
background-color: #4CAF50;
color: white;
/* remove text decoration (underline) */
text-decoration: none;
}
li a:hover:not(:active) {
/* during the unselected, mouse-hover phase */
background-color: #555;
color: white;
/* remove text decoration (underline) */
text-decoration: none;
}
</style>
<ul>
<li><a>Menu Home</a></li>
<li><a>Projects</a></li>
</ul>

For a horizontal navigation bar, write it like this:

<style>
ul {
width: 100%;
list-style-type: none;
margin: 0;
padding: 0;
background-color: #f1f1f1;
/* hide scrollbar */
overflow: hidden;
/* flex layout */
display: flex;
}
/* set an extra li layout */
li {
/* float the element to the left */
float: left;
/* flex layout splits equally */
flex: 1;
}
li a {
color: #000;
padding: 15px 0;
display: block;
text-decoration: none;
/* horizontally center text */
text-align: center;
}
/* same as below */
li a:active {
background-color: #4CAF50;
color: white;
text-decoration: none;
}
li a:hover:not(:active) {
background-color: #555;
color: white;
text-decoration: none;
}
</style>
<ul>
<li><a>Menu Home</a></li>
<li><a>Projects</a></li>
</ul>

Implement a dropdown menu:

  1. Define a button that shows the dropdown menu on mouse hover and ideally changes color.
  2. Define a dropdown menu (content that is directly visible).
<style>
/* dropdown button style */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
/* remove border */
border: none;
/* use a pointer cursor (turn the mouse into a hand) */
cursor: pointer;
}
/* container <div> - positions the dropdown content */
.dropdown {
/* relative position */
position: relative;
}
/* dropdown content (hidden by default) */
.dropdown-content {
/* hidden */
display: none;
/* absolute position */
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
/* add a background shadow to the dropdown content */
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
/* if right-aligned (currently left-aligned) */
/* right:0; */
}
/* dropdown menu links (content) */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* change the dropdown link color on mouse hover */
.dropdown-content a:hover {
background-color: #f1f1f1
}
/* show the dropdown menu on mouse hover */
.dropdown:hover .dropdown-content {
display: block;
}
/* change the dropdown button's background color once the dropdown content is shown */
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
</style>
<div class="dropdown">
<button class="dropbtn">Dropdown Menu</button>
<div class="dropdown-content">
<a>Option 1</a>
</div>
</div>

Tip: you can also place images, etc. inside a dropdown menu.

Tooltip

<style>
/* tooltip element */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
/* tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
/* box rounded corners */
border-radius: 6px;
padding: 5px 0;
position: absolute;
/* stacking level, meaning above most other elements */
z-index: 1;
/* offset relative to the normal position (5px up because padding is 5px) */
top: -5px;
/* means positioned at 110% of the containing element's width (i.e. slightly beyond the right edge), showing the tooltip to the right of the trigger element */
left: 110%;
For the left side use right: 110%
For the top use bottom: 100% but also set centering: left: 50%; margin-left: -60px; (half the offset width)
For the bottom use top: 100% but also set centering: left: 50%; margin-left: -60px; (half the offset width)
/* fade in: start from opacity 0 */
opacity: 0;
transition: opacity 1s;
}
/* triangle style, worth remembering */
.tooltip .tooltiptext::after {
/* use the after pseudo-element to add content after the element, here a triangle */
content: ""; /* no text needed */
position: absolute;
/* vertically centered */
top: 50%;
/* the right edge of the element is at 100% of its containing block's width, on the left side of the tooltip */
right: 100%;
margin-top: -5px;
border-width: 5px;
border-style: solid;
/* order is top right bottom left; leveraging CSS border behavior, when adjacent border colors differ a beveled effect is produced */
border-color: transparent black transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
/* fade in: opacity becomes 1 */
opacity: 1;
}
</style>
<div class="tooltip">Move mouse here
<span class="tooltiptext">Tooltip text</span>
</div>
Move mouse here Tooltip text

Thanks for reading! Follow me if you'd like~

CSS

Tue Jun 28 2005
4679 words · 45 minutes
Cover
Sample track
Sample artist
Cover
Sample track
Sample artist
0:00 / 0:00