CSS Volume 1
版权声明:署名-非商业性使用-相同方式共享
What is CSS?
- CSS stands for Cascading Style Sheets
- CSS describes how HTML elements are to be displayed on screen, paper, or in other media
- CSS saves a lot of work. It can control the layout of multiple web pages all at once
- External stylesheets are stored in CSS files
CSS Solved a Big Problem
HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>
, and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large websites, where fonts and color information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS removed the style formatting from the HTML page!
CSS Syntax
A CSS rule consists of a selector and a declaration block.
The selector points to the HTML element you want to style.
The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly braces.
p {
color: red;
text-align: center;
}
CSS Comments
Comments are used to explain the code, and may help when you edit the source code at a later date.
Comments are ignored by browsers.
/* This is
a multi-line
comment */
p {
color: red; /* Set text color to red */
}
Three Ways to Insert CSS
There are three ways of inserting a style sheet:
-
External CSS
<html> <head> <link rel="stylesheet" href="mystyle.css"> </head> <body> ... </body> </html>
-
Internal CSS
<style> body { background-color: linen; } h1 { color: maroon; margin-left: 40px; } </style>
-
Inline CSS
<html> <body> <h1 style="color:blue; text-align:center;">This is a heading</h1> <p style="color:red;">This is a paragraph.</p> </body> </html>
Multiple Style Sheets
If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used.
Cascading Order
What style will be used when there is more than one style specified for an HTML element?
All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where number one has the highest priority:
- Inline style (inside an HTML element)
- External and internal style sheets (in the head section)
- Browser default
So, an inline style has the highest priority, and will override external and internal styles and browser defaults.
CSS Selectors
@@ Tags: 选择器
CSS selectors are used to "find" (or select) the HTML elements you want to style.
We can divide CSS selectors into five categories:
- Simple selectors
Select elements based on name, id, class - Combinator selectors(组合选择器)
Select elements based on a specific relationship between them - Pseudo-class selectors
Select elements based on a certain state - Pseudo-elements selectors
Select and style a part of an element - Attribute selectors
Select elements based on an attribute or attribute value
CSS Selectors examples:
- The CSS element Selector
- The element selector selects HTML elements based on the element name.
p{}
- The CSS id Selector
- The id selector uses the id attribute of an HTML element to select a specific element.
- The id of an element is unique within a page, so the id selector is used to select one unique element!
#para1{}
- The CSS class Selector
- The class selector selects HTML elements with a specific class attribute.
- To select elements with a specific class, write a period (.) character, followed by the class name.
.center{}
p.center{}
- The CSS Universal Selector
- The universal selector (*) selects all HTML elements on the page.
*{}
- The CSS Grouping Selector
- The grouping selector selects all the HTML elements with the same style definitions.
h1, h2, p{}
其他四种选择器参见: 《CSS Volume 2》
CSS Colors
Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.
CSS Color Names
In CSS, a color can be specified by using a predefined color name:
- Tomato
- Orange
- DodgerBlue
- MediumSeaGreen
- Gray
- SlateBlue
- Violet
- LightGray
CSS/HTML support 140 standard color names.
- RGB Value
- An RGB color value represents RED, GREEN, and BLUE light sources.
- Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.
rgb(red, green, blue)
- RGBA Value
- The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all).
rgba(red, green, blue, alpha)
- HEX Colors
- A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color.
#000000
#ffffff
- 3 Digit HEX Value
- The 3-digit hex code is a shorthand for some 6-digit hex codes.
- The 3-digit hex code has the following form: #rgb.
- Where r, g, and b represent the red, green, and blue components with values between 0 and f.
- The 3-digit hex code can only be used when both the values (RR, GG, and BB) are the same for each component. So, if we have #ff00cc, it can be written like this: #f0c.
#fc9 /* same as #ffcc99 */
#f0f /* same as #ff00ff */
- HSL Value
- HSL stands for hue, saturation, and lightness.
- In CSS, a color can be specified using hue, saturation, and lightness (HSL) in the form:
hsl(hue, saturation, lightness)
. - Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.
- Saturation is a percentage value. 0% means a shade of gray, and 100% is the full color.
- Lightness is also a percentage. 0% is black, 50% is neither light or dark, 100% is white.
hsl(39, 100%, 50%)
hsl(240, 100%, 50%)
- HSLA Value
- An HSLA color value is specified with:
hsla(hue, saturation, lightness, alpha)
. - The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all).
hsla(9, 100%, 64%, 0)
hsla(9, 100%, 64%, 0.6)
- An HSLA color value is specified with:
CSS Backgrounds
The CSS background properties are used to add background effects for elements.
background-color
background-image
- The background-image property specifies an image to use as the background of an element.
- By default, the image is repeated so it covers the entire element.
background-repeat
repeat-x
repeat-y
no-repeat
background-position
- This property is used to specify the position of the background image.
background-attachment
- This property specifies whether the background image should scroll or be fixed (will not scroll with the rest of the page).
fixed
scroll
background
(shorthand property)background: #ffffff url("img_tree.png") no-repeat right top;
- When using the shorthand property the order of the property values is:
CSS Borders
The CSS border properties allow you to specify the style, width, and color of an element's border.
CSS Border Style
@@ Refer: https://www.w3schools.com/css/css_border.asp
The border-style
property specifies what kind of border to display.
The following values are allowed:
dotted
- Defines a dotted borderdashed
- Defines a dashed bordersolid
- Defines a solid borderdouble
- Defines a double bordergroove
- Defines a 3D grooved border. The effect depends on the border-color valueridge
- Defines a 3D ridged border. The effect depends on the border-color valueinset
- Defines a 3D inset border. The effect depends on the border-color valueoutset
- Defines a 3D outset border. The effect depends on the border-color valuenone
- Defines no borderhidden
- Defines a hidden border
The border-style
property can have from one to four values (for the top border, right border, bottom border, and the left border).
CSS Border Width
- The border-width property specifies the width of the four borders.
- The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the three pre-defined values: thin, medium, or thick.
border-width: 5px 20px; /* 5px top and bottom, 20px on the sides */
border-width: 25px 10px 4px 35px; /* 25px top, 10px right, 4px bottom and 35px left */
CSS Border - Shorthand Property
The border
property is a shorthand property for the following individual border properties:
border-width
border-style
(required)border-color
CSS Rounded Borders
The border-radius
property is used to add rounded borders to an element.
p {
border: 2px solid red;
border-radius: 5px;
background: green;
}
CSS Margins
@@ Tags: 外边距
The CSS margin
properties are used to create space around elements, outside of any defined borders.
With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).
Margin
CSS has properties for specifying the margin for each side of an element:
margin-top
margin-right
margin-bottom
margin-left
All the margin properties can have the following values:
- auto - the browser calculates the margin
- length - specifies a margin in px, pt, cm, etc.
- % - specifies a margin in % of the width of the containing element
- inherit - specifies that the margin should be inherited from the parent element
Tip: Negative values are allowed.
The auto Value
@@ Tags: 水平居中;垂直居中
You can set the margin property to auto to horizontally center the element within its container.
The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
div {
width: 300px;
margin: auto;
border: 1px solid red;
}
注意:
- 不能使用
margin-top:auto
或margin-bottom:auto
来居中元素, 因为在他们的值会被计算为0
. - 但当父容器为
display: flex;
时,margin: auto auto
将水平及垂直居中. - 尽管如此, 但仍然建议使用
align-items: center;
或justify-content: center;
. - 参考: Using margin:auto to vertically-align a div
Margin Collapse
@@ Tags: 折叠;重叠;塌陷
@@ Refer: https://www.w3schools.com/css/css_margin_collapse.asp
Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins.
This does not happen on left and right margins! Only top and bottom margins!
CSS Padding
@@ Tags: 内边距
The CSS padding properties are used to generate space around an element's content, inside of any defined borders.
With CSS, you have full control over the padding. There are properties for setting the padding for each side of an element (top, right, bottom, and left).
Padding and Element Width
The CSS width
property specifies the width of the element's content area. The content area is the portion inside the padding, border, and margin of an element (the box model).
So, if an element has a specified width, the padding added to that element will be added to the total width of the element. This is often an undesirable result.
CSS Outline
An outline is a line that is drawn around elements, OUTSIDE the borders, to make the element "stand out".
p {
outline: #4CAF50 solid 10px;
}
Note: Outline differs from borders! Unlike border, the outline is drawn outside the element's border, and may overlap other content. Also, the outline is NOT a part of the element's dimensions; the element's total width and height is not affected by the width of the outline.
CSS Outline Offset
The outline-offset
property adds space between an outline and the edge/border of an element. The space between an element and its outline is transparent.
CSS Text
CSS has a lot of properties for formatting text.
color
background-color
text-align
- center
- left
- right
- justify(两边对齐)
text-align-last
This property specifies how to align the last line of a text.direction
unicode-bidi
Used together with the direction property to set or return whether the text should be overridden to support multiple languages in the same documentvertical-align
- baseline
- text-top
- text-nottom
- sub
- super
text-decoration
text-decoration: underline red double 5px;
text-decoration-line
This property is used to add a decoration line to text.- overline
- line-through
- underline
text-decoration-color
This property is used to set the color of the decoration line.text-decoration-style
This property is used to set the style of the decoration line.text-decoration-thickness
This property is used to set the thickness of the decoration line.text-transform
This property is used to specify uppercase and lowercase letters in a text.- upercase
- lowercase
- capitalize(首字母大写)
text-indent
This property is used to specify the indentation(缩进) of the first line of a text.letter-spacing
This property is used to specify the space between the characters in a text(文本中字符的间距).line-height
This property is used to specify the space between lines.Word Spacing
This property is used to specify the space between the words in a text.white-space
This property specifies how white-space inside an element is handled(决定是否换行).text-shadow
- This property adds shadow to text.
text-shadow: 2px 2px red;
text-shadow: 2px 2px 5px red;
CSS Fonts
@@ Tags: 字体
@@ Refer: https://www.w3schools.com/css/css_font.asp
Choosing the right font for your website is important!
CSS Font Property
The font property is a shorthand property for:
- font-style
- font-variant
- font-weight
- font-size/line-height
- font-family
Note: The font-size and font-family values are required. If one of the other values is missing, their default value are used.
font: 20px Arial, sans-serif;
font: italic small-caps bold 12px/30px Georgia, serif;
Generic Font Families
In CSS there are five generic font families:
- Serif(衬线字体)
This fonts have a small stroke(笔画) at the edges of each letter. They create a sense of formality and elegance. - Sans-serif(无衬线体)
This fonts have clean lines (no small strokes attached). They create a modern and minimalistic look. - Monospace(等宽字体)
here all the letters have the same fixed width. They create a mechanical look. - Cursive(手写体)
This fonts imitate human handwriting. - Fantasy(幻想体/装饰体)
This fonts are decorative/playful fonts.
Difference Between Serif and Sans-serif Fonts
Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.
CSS Web Safe Fonts
- Arial (sans-serif)
- Arial is the most widely used font for both online and printed media. Arial is also the default font in Google Docs.
- Arial is one of the safest web fonts, and it is available on all major operating systems.
- Verdana (sans-serif)
Verdana is a very popular font. Verdana is easily readable even for small font sizes. - Tahoma (sans-serif)
The Tahoma font has less space between the characters. - Trebuchet MS (sans-serif)
Trebuchet MS was designed by Microsoft in 1996. Use this font carefully. Not supported by all mobile operating systems. - Times New Roman (serif)
Times New Roman is one of the most recognizable fonts in the world. It looks professional and is used in many newspapers and "news" websites. It is also the primary font for Windows devices and applications. - Georgia (serif)
Georgia is an elegant serif font. It is very readable at different font sizes, so it is a good candidate for mobile-responsive design. - Garamond (serif)
Garamond is a classical font used for many printed books. It has a timeless look and good readability. - Courier New (monospace)
Courier New is the most widely used monospace serif font. Courier New is often used with coding displays, and many email providers use it as their default font. Courier New is also the standard font for movie screenplays. - Brush Script MT (cursive)
The Brush Script MT font was designed to mimic handwriting. It is elegant and sophisticated, but can be hard to read. Use it carefully.
CSS Font-Family
In CSS, we use the font-family
property to specify the font of a text.
Note: If the font name is more than one word, it must be in quotation marks, like: "Times New Roman".
Tip: The
font-family
property should hold several font names as a "fallback" system, to ensure maximum compatibility between browsers/operating systems. Start with the font you want, and end with a generic family (to let the browser pick a similar font in the generic family, if no other fonts are available). The font names should be separated with comma.
CSS Font Fallbacks(回退)
@@ Tags: 字体回退;备选字体
@@ Refer: https://www.w3schools.com/css/css_font_fallbacks.asp
为了保证字体在不同的设备上都能够正常显示,可以在font-family
属性中指定多个备选字体,以便在用户设备上如果缺失该字体,可以自动使用备选字体来替代。
p {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
CSS Font Style
font-style
property is mostly used to specify italic text, and has three values:- normal - The text is shown normally
- italic - The text is shown in italics
- oblique - The text is "leaning" (oblique is very similar to italic, but less supported),
font-weight
property specifies the weight of a font:font-weight: normal;
font-weight: bold;
font-variant
- This property specifies whether or not a text should be displayed in a small-caps font.
- In a small-caps font, all lowercase letters are converted to uppercase letters. However, the converted uppercase letters appears in a smaller font size than the original uppercase letters in the text.
font-variant: normal;
font-variant: small-caps;
, Try it.
CSS Font Size
This property sets the size of the text.
Being able to manage the text size is important in web design. However, you should not use font size adjustments to make paragraphs look like headings, or headings look like paragraphs.
Always use the proper HTML tags, like<h1> - <h6>
for headings and<p>
for paragraphs.
The font-size value can be an absolute, or relative size.
Absolute size:
- Sets the text to a specified size
- Does not allow a user to change the text size in all browsers (bad for accessibility reasons)
- Absolute size is useful when the physical size of the output is known
Relative size:
- Sets the size relative to surrounding elements
- Allows a user to change the text size in browsers
Set Font Size With Pixels
Setting the text size with pixels gives you full control over the text size:
h1{ font-size: 40px; }
h2{ font-size: 30px; }
p{ font-size: 14px; }
Tip: If you use pixels, you can still use the zoom tool to resize the entire page.
Set Font Size With Em
To allow users to resize the text (in the browser menu), many developers use em instead of pixels.
1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.
The size can be calculated from pixels to em using this formula: pixels/16=em.
h1{ font-size: 2.5em; /* 40px/16=2.5em */ }
h2{ font-size: 1.875em; /* 30px/16=1.875em */ }
p{ font-size: 0.875em; /* 14px/16=0.875em */ }
In the example above, the text size in em is the same as the previous example in pixels. However, with the em size, it is possible to adjust the text size in all browsers.
Unfortunately, there is still a problem with older versions of Internet Explorer. The text becomes larger than it should when made larger, and smaller than it should when made smaller.
Use a Combination of Percent and Em
The solution that works in all browsers, is to set a default font-size in percent for the <body>
element:
body{ font-size: 100%; }
h1{ font-size: 2.5em; }
h2{ font-size: 1.875em; }
p{ font-size: 0.875em; }
Responsive Font Size
The text size can be set with a vw unit, which means the "viewport width".
That way the text size will follow the size of the browser window.
Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.
CSS Google Fonts
If you do not want to use any of the standard fonts in HTML, you can use Google Fonts.
Google Fonts are free to use, and have more than 1000 fonts to choose from.
Just add a special style sheet link in the <head>
section and then refer to the font in the CSS.
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Audiowide|Sofia|Trirong">
<style>
h1.a {font-family: "Audiowide", sans-serif;}
h1.b {font-family: "Sofia", sans-serif;}
h1.c {font-family: "Trirong", serif;}
</style>
</head>
For a list of all available Google Fonts, visit our How To - Google Fonts Tutorial.
CSS Font Pairings(搭配)
@@ Refer: https://www.w3schools.com/css/css_font_pairings.asp
Great font pairings are essential to great design.
优秀的字体搭配对于优秀的设计至关重要。
Here are some basic rules to create great font pairings:
-
Complement(互补)
- It is always safe to find font pairings that complement one another.
- A great font combination should harmonize, without being too similar or too different.
-
Use Font Superfamilies(超级字体家族)
- A font superfamily is a set of fonts designed to work well together. So, using different fonts within the same superfamily is safe.
- For example, the Lucida superfamily contains the following fonts: Lucida Sans, Lucida Serif, Lucida Typewriter Sans, Lucida Typewriter Serif and Lucida Math.
-
Contrast is King(反差为王)
- Two fonts that are too similar will often conflict. However, contrasts, done the right way, brings out the best in each font.
- Example: Combining serif with sans serif is a well known combination.
- A strong superfamily includes both serif and sans serif variations of the same font (e.g. Lucida and Lucida Sans).
-
Choose Only One Boss
- One font should be the boss. This establishes a hierarchy for the fonts on your page. This can be achieved by varying the size, weight and color.
CSS Icons
@@ Refer: https://www.w3schools.com/css/css_icons.asp
Icons can easily be added to your HTML page, by using an icon library.
CSS Links
Links can be styled with any CSS property (e.g. color, font-family, background, etc.).
In addition, links can be styled differently depending on what state they are in.
The four links states are:
a:link
- a normal, unvisited linka:visited
- a link the user has visiteda:hover
- a link when the user mouses over ita:active
- a link the moment it is clicked
When setting the style for several link states, there are some order rules:
- a:hover MUST come after a:link and a:visited
- a:active MUST come after a:hover
CSS Lists
@@ Tags: 有序列表;无序列表
In HTML, there are two main types of lists:
- unordered lists
<ul>
- the list items are marked with bullets - ordered lists
<ol>
- the list items are marked with numbers or letters
The CSS list properties allow you to:
- Set different list item markers for ordered lists
- Set different list item markers for unordered lists
- Set an image as the list item marker
- Add background colors to lists and list items
CSS List Properties
list-style-type
specifies the type of list item marker.none
allcircle
ulsquare
ulupper-roman
ollower-alpha
ol
list-style-image
specifies an image as the list item marker.
如果指定的值因为某种原因无法显示则将会显示list-style-type
的值.list-style-position
specifies the position of the list-item markers (bullet points).outside
means that the bullet points will be outside the list item. The start of each line of a list item will be aligned vertically(default).inside
means that the bullet points will be inside the list item. As it is part of the list item, it will be part of the text and push the text at the start.- Try it
list-style
this property is a shorthand property, the order of the property values are:list-style-type
list-style-position
list-style-image
CSS Tables
border-collapse
This property sets whether the table borders should be collapsed into a single border.vertical-align
This property sets the vertical alignment (like top, bottom, or middle(default)) of the content in<th>
or<td>
.:hover
Use the :hover selector on<tr>
to highlight table rows on mouse over.nth-child()
- For zebra-striped tables, use the
nth-child()
selector and add abackground-color
to all even (or odd) table rows. tr:nth-child(even) {background-color: #f2f2f2;}
- For zebra-striped tables, use the
border-spacing
- This property sets the distance between the borders of adjacent cells(水平间距, 垂直间距).
- Note: This property works only when
border-collapse
is separate.
empty-cells
Specifies whether or not to display borders and background on empty cells in a table.- top
- bottom
- table-layout
- This property defines the algorithm used to lay out table cells, rows, and columns.
- Tip: The main benefit of
table-layout: fixed;
is that the table renders much faster. On large tables, users will not see any part of the table until the browser has rendered the whole table. So, if you usetable-layout: fixed
, users will see the top of the table while the browser loads and renders rest of the table. This gives the impression that the page loads a lot quicker!
- Responsive Table
- A responsive table will display a horizontal scroll bar if the screen is too small to display the full content.
- Add a container element (like
<div>
) withoverflow-x:auto
around the<table>
element to make it responsive.
CSS Layout
CSS display Property
@@ Tags: CSS Dispaly
@@ Refer: https://developer.mozilla.org/en-US/docs/Web/CSS/display
The display
property is the most important CSS property for controlling layout.
The display
property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is block
or inline
.
- Block-level Elements
- A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
- Inline Elements
- An inline element does not start on a new line and only takes up as much width as necessary.
display: inline-block
Compared to display: inline
, the major difference is that display: inline-block
allows to set a width and height on the element.
Also, with display: inline-block
, the top and bottom margins/paddings are respected(重视), but with display: inline
they are not.
Compared to display: block
, the major difference is that display: inline-block
does not add a line-break after the element, so the element can sit next to other elements.
Display: none
display: none;
is commonly used with JavaScript to hide and show elements without deleting and recreating them.
display:none
or visibility:hidden
?
@@ Tags: 隐藏元素
@@ Refer: https://www.w3schools.com/css/css_display_visibility.asp
Hiding an element can be done by setting the display property to none. The element will be hidden, and the page will be displayed as if the element is not there:
visibility:hidden;
also hides an element.
However, the element will still take up the same space as before. The element will be hidden, but still affect the layout.
Override The Default Display Value
display: inline;
display: block;
Note: Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is. So, an inline element with
display: block
; is not allowed to have other block elements inside it.
width and max-width(Using width, max-width and margin: auto;)
A block-level element always takes up the full width available (stretches out to the left and right as far as it can).
Setting the width
of a block-level element will prevent it from stretching out to the edges of its container. Then, you can set the margins
to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins.
Note: The problem with the
<div>
above occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.Using
max-width
instead, in this situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices.
The position Property
@@ Tags: position;绝对定位;相对定位;黏性定位;固定定位
The position
property specifies the type of positioning(定位) method used for an element (static, relative, fixed, absolute or sticky).
Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the position value.
position: static;
- HTML elements are positioned static by default.
- Static positioned elements are not affected by the top, bottom, left, and right properties.
- An element with
position: static;
is not positioned in any special way; it is always positioned according to the normal flow of the page.
position: relative;
- An element with
position: relative;
is positioned relative to its normal position. - Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.
- An element with
position: fixed;
- An element with
position: fixed;
is positioned relative to the viewport(视口), which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.
- An element with
position: absolute;
- An element with
position: absolute;
is positioned relative to the nearest positioned ancestor(定位祖先) (instead of positioned relative to the viewport, like fixed). - However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with(随同...一起) page scrolling(即: 固定在body上, 并将跟随页面滚动而滚动).
- Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
- 类似于
fixed
,absolute
相对固定于定位祖先(非static的父容器), 前者相对固定于视口. - Try it Yourself.
- An element with
position: sticky;
- An element with
position: sticky;
is positioned based on the user's scroll position. - A sticky element toggles between
relative
andfixed
, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed). - 当滚动条位置满足条件时元素切换为固定, 否则是相对放置.
- Note: Internet Explorer does not support sticky positioning. Safari requires a
-webkit-
prefix. You must also specify at least one of top, right, bottom or left for sticky positioning to work. - Try it Yourself.
- An element with
The z-index Property
When elements are positioned, they can overlap other elements.
The z-index
property specifies the stack order of an element (which element should be placed in front of, or behind, the others).
An element can have a positive or negative stack order.
An element with greater stack order is always above an element with a lower stack order.
Note:
z-index
only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display: flex elements).If two positioned elements overlap each other without a
z-index
specified, the element defined last in the HTML code will be shown on top.
CSS Overflow
The overflow
property specifies whether to clip the content or to add scrollbars when the content of an element is too big to fit in the specified area.
The overflow
property has the following values:
visible
- Default. The overflow is not clipped. The content renders outside the element's box.hidden
- The overflow is clipped, and the rest of the content will be invisible.scroll
- The overflow is clipped, and a scrollbar is added to see the rest of the content.auto
- Similar toscroll
, but it adds scrollbars only when necessary.
Note: The
overflow
property only works for block elements with a specified height.Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though "overflow:scroll" is set).
overflow-x and overflow-y
The overflow-x
and overflow-y
properties specifies whether to change the overflow of content just horizontally or vertically (or both):
overflow-x
specifies what to do with the left/right edges of the content.overflow-y
specifies what to do with the top/bottom edges of the content.
overflow-wrap
The property specifies whether or not the browser can break lines with long words, if they overflow the container.
normal
Long words will not break, even if they overflow the container. This is default.anywhere
Long words will break if they overflow the container.break-word
Long words will break if they overflow the container.
Float and Clear
The float Property
@@ Refer: https://www.w3schools.com/css/css_float.asp
The float
property is used for positioning and formatting content e.g. let an image float left to the text in a container.
The float
property can have one of the following values:
left
- The element floats to the left of its containerright
- The element floats to the right of its containernone
- The element does not float (will be displayed just where it occurs in the text). This is defaultinherit
- The element inherits the float value of its parent
In its simplest use, the float
property can be used to wrap text around images.
Note: Absolutely positioned elements ignore the float property!
Note: Elements next to a floating element will flow around it. To avoid this, use the clear property or the clearfix hack.
杂注
-
float称为浮动元素
-
float可对行元素和块元素生效(生效后元素的display为block)
-
float会让元素脱离正常文档流, 移动到其父容器中指定的位置(左或右, padding指定的内边距内).
-
float元素脱离正常文档流后, 不会在父容器占用高度, 也就是说: 父容器的所有子元素都为
float
, 则容器高度为0, 因此后面的元素将从父容器的高度开始排布. -
float元素虽然脱离了正常文档流, 但不会与正常文档流中的元素重叠, 而是彼此配合占用可用的空间- 会重叠try it
if float:left then if 在父容器中存在上一个元素 then if 上一个元素是浮动元素 then 元素移动到容器的左边, 排在上一个浮动(left)元素右边, 并保持top对齐; else then 元素移动到容器的左边, top保持在上一个元素下边; end if else then 元素移动到容器的左边 end if end if
Clear and Clearfix
When we use the float
property, and we want the next element below (not on right or left), we will have to use the clear
property.
The clear
property specifies what should happen with the element that is next to a floating element.(该属性指定:浮动元素的姊妹元素的排放逻辑)
The clear
property can have one of the following values:
none
- The element is not pushed below left or right floated elements. This is defaultleft
- The element is pushed below left floated elementsright
- The element is pushed below right floated elementsboth
- The element is pushed below both left and right floated elementsinherit
- The element inherits the clear value from its parent
If a floated element is taller than the containing element, it will "overflow" outside of its container. We can then add a clearfix hack to solve this problem:
The overflow: auto
clearfix works well as long as(只要) you are able to keep control of(控制) your margins and padding (else you might see scrollbars).
The new, modern clearfix hack however, is safer to use, and the following code is used for most webpagestry it:
.clearfix::after {
content: "";
clear: both;
display: table;
}
CSS Layout Float Examples
@@ Refer: https://www.w3schools.com/css/css_float_examples.asp
Grid of Boxes / Equal Width Boxes
* {
box-sizing: border-box;
}
.box {
float: left;
width: 33.33%; /* three boxes (use 25% for four, and 50% for two, etc) */
padding: 50px; /* if you want space between the images */
}
What is box-sizing?
You can easily create three floating boxes side by side(并排). However, when you add something that enlarges(扩大) the width of each box (e.g. padding or borders), the box will break. The
box-sizing
property allows us to include the padding and border in the box's total width (and height), making sure that the padding stays inside of the box and that it does not break.You can read more about the box-sizing property in our CSS Box Sizing Chapter.
Equal Height Boxes
However, it is not easy to create floating boxes with equal heights. A quick fix however, is to set a fixed height.
.box {
height: 500px;
}
However, this is not very flexible. It is ok if you can guarantee(确保) that the boxes will always have the same amount of content in them. But many times, the content is not the same. If you try the example above on a mobile phone, you will see that the second box's content will be displayed outside of the box. This is where CSS3 Flexbox comes in handy(派上用场) - as it can automatically stretch boxes to be as long as the longest box:
Tip: You can read more about the Flexbox Layout Module in our CSS Flexbox Chapter.
CSS Layout - Horizontal & Vertical Align
- Center Align Elements
margin: auto; witdth: 50%
- Center Align Text
text-align: center;
- Center an Image
- set left and right margin to auto and make it into a block element.
- Left and Right Align - Using position
position: absolute; right: 0px;
- Left and Right Align - Using float
float: right;
- Center Vertically - Using padding
padding: 70px 0;
- Center Vertically - Using line-height
line-height: 200px;
- Center Vertically - Using position & transform
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
- Center Vertically - Using Flexbox
display: flex; justify-content: center; align-items: center;
CSS Responsive Web Design
@@ Tags: 响应式
@@ Refer: https://www.w3schools.com/css/css_rwd_intro.asp
通过设置相对宽度与媒体查询来响应不同的窗口尺寸
/* Create three equal columns that floats next to each other */
.column {
float: left;
width: 33.33%;
padding: 15px;
}
/* Clear floats after the columns */
.row::after {
content: "";
display: table;
clear: both;
}
/* Responsive layout - makes the three columns stack on top of each other instead of next to each other */
@media screen and (max-width:600px) {
.column {
width: 100%;
}
}
Comments ()