Contains an overview of CSS covered in the Codecademy Web Path courses and links to Mozilla documentation.
Contents
- Basic CSS language rules
- Setting page layouts
- The Box Model
- Changing the Box Model
- Controlling and positioning of elements on a web page.
- <length> - units for sizing and positioning -
px, em rem, %, auto
, etc - Flexbox layouts
- Overview of flexbox properties
justify-content
: [et al]
-main-axis
justify contents along containeralign-items
: [et al]
- flex-boxcross-axis
(gridlayoutblock-axis
) align single-row contentsflex-grow
: [n]
-main-axis
grow item proportionally to siblings, using parent's extra spaceflex-shrink
: [n]
-main-axis
shrinkitem
proportionally to siblings, when parent container too smallflex-basis
: [auto | unit ]
- set initial size of item alongmain-axis
flex
: [auto | initial | none | units]
- combines grow, shrink and basis settings onmain-axis
flex-wrap
: [wrap | nowrap | wrap-reverse ]
- sets wrapping of contained items alongmain-axis
, when container has insufficient spacealign-content
: [et al]
- flex-boxcross-axis
(gridlayoutblock-axis
) align multi-row contentsflex-direction
: [row | row-reverse | column | column-reverse]
- setmain-axis
and direction.flex-flow
: [flex-direction | flex-wrap]
- combines flex-wrap and flex-direction settings
- Colors
- Typography
- Detecting browser information with
@media
rules - Creating responsive websites
- Design patterns
- Tips and trips
- From highest to lowest;
Order of precedence |
Name | Example CSS selector | Example corresponding HTML |
---|---|---|---|
1 | ID | #my-element-id {...} |
<p id="cmy-element-id">...</p> |
2 | chained | h1.my-class {...} |
<h1 class="my-class">...</div> |
3 | class | .my-class-2 {...} |
<div class="my-class-2">...</div> |
4 | nested element | footer h3 {...} |
<footer><h3>...</h3></footer> |
5 | element | h2 {...} |
<h2>...</h2> |
- The five properties of the box model are:
height
andwidth
,padding
,borders
, andmargins
. - The box model uses the five properties to create space around and between HTML elements;
- See here for the fixed and relative units that can be used to set the properities.
Property | Effect |
---|---|
height [1] width [1] min-width max-width min-height max-height |
Sets content area. NB: Can combine min & max to limit scaling in two directions. E.g. div.container { min-height: 150px; max-height: 600px; min-width: 300px; max-width: 900px; } |
border |
Surrounds the content area and padding of an element. The color, style, and thickness of a border can be set with CSS properties. E.g. border: 3px solid #eb6536 sets line width, type of line, andcolor of line |
padding [1] padding-top , padding-bottom , padding-right , padding-right |
Sets the spacing between the content area and the border. For padding , the number of arguments changes which faces the arg(s)apply to. |
margin [1] margin-top , margin-bottom , margin-right , margin-left |
Sets the spacing outside of an element's border; 1) For margin , the number of arguments changes which faces the arg(s) apply to. 2) margin: 0 auto sets no top-bottom margins, but horizontallycenters an element inside of its parent content area, if it has a width. 3) Vertical margin collapse; - Vertical margins collapse, so the space between vertically adjacent elements is equal to the larger margin. - Horizontal margins add, so the total space between the borders of adjacent elements is equal to the sum of the right margin of one element and the left margin of the adjacent element. |
overflow |
Property can be set to display , hide , or scroll , and dictates howHTML will render content that overflows its parent's content area. |
visibility |
Property can hide or show elements. |
[1] WARNING: If the element display
defaults to, or is set to, inline
, it causes the element to be as small as possible and hence partially, or fully, negates any height
, width
, padding
and margin
settings.
The number of arguments changes which faces the arguments apply to as follows;
Args | Faces Applied To | Example |
---|---|---|
1 | All four faces. | padding: 20px; |
2 | 1st: Top & bottom 2nd: Both sides |
margin: 10px 20px; |
3 | 1st: Top 2nd: Both sides 3rd: Bottom |
padding: 10px 20px; 5px; |
4 | 1st: Top 2nd: Right side 3rd: Bottom 4th: Left side |
margin: 10px 20px 5px 50px; |
box-sizing
: [content-box (default) | border-box]
The box-sizing property controls the box model used by the browser;
display
: [inline | block | inline-block]
- The display property allows control of how an element flows vertically and horizontally.
Setting | Effect |
---|---|
inline |
Elements take up the minimum size required to contain the contents and cannot be altered in size with the height or width properties. See here for more. |
block |
Elements fill the entire width of the page by default, but their width property can also be set. Unless otherwise specified, they are the height necessary to accommodate their content. The main block-by-default elements are <h1> through <h6>, <p>, <div> and <footer> , see here for more. |
inline-block |
Elements can also appear next to each other, can have set width and height ,and do not take up their entire container width. |
flex |
Elements will remain block level — no other elements will appear on the same line as it. |
inline-flex |
Elements will be flex containers that are also inline elements. |
position
: [static (default) | relative | absolute | fixed]
Setting | Effect |
---|---|
static |
Default value. Elements render in order, as they appear in the document flow |
relative |
Position relative to its default position on the page. |
absolute |
Position relative to its first positioned (not static) ancestor element. It can be pinned to any part of the web page, but the element will still move with the rest of the document when the page is scrolled. |
fixed |
Position pinned to any part of the web page. The element will remain in view no matter what. If an element's position is fixed ;1) The element may be obscured underneath others, so z-index: <a_suitably_big_int> can bring the element forward. Which may in turn obscure other element(s), which then need to have their position altered to be visiable again. e.g. Set their position:relative , and then push them down using top:<the_height_of_the_obscuring_element>px .2) The element may shrink, which width: 100% can address, provided the display for the element is not inline . |
sticky |
Position relative to its default position on the page until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block. |
- Once
position
is changed fromstatic
, the element's position can be modified using thetop
,bottom
,left
,right
properties, usingauto
,inherit
, or any of these units.
z-index
: [int]
- The
z-index
of an element specifies how far back or how far forward an element appears on the page when it overlaps other elements. - The higher the number, the closer to the top of the stack
- WARNING: z-index will not function if position either defaults, or is set to, static.
- See also Using z-index article
float
: [left | right]
- Move elements as far
left
orright
as possible. - Floated elements must have a
width
specified, otherwise the element will assume the full width of its containing element, and changing the float value will not yield any visible results. - The float property can also be used to float multiple elements at once. However, when multiple floated elements have different heights, it can affect their layout on the page. Specifically, elements can "bump" into each other and not allow other elements to properly move the left or right.
clear
: [left | right | both]
-
When multiple
floated
elements have different heights, they can "bump" into each other and not allow other elements to properly move to the left or right. -
The
clear
property specifies how elements should behave when they bump into each other on the page.
Setting | Effect |
---|---|
left |
The left side of the element will not touch any other element within the same containing element. |
right |
The right side of the element will not touch any other element within the same containing element. |
both |
Neither side of the element will touch any other element within the same containing element. |
none |
The element can touch either side. |
<length> - units for sizing and positioning - px, em rem, %, auto
, etc
- Units can be applied when sizing and positioning elements and their contents
- Absolute units represent a physical measurement when the physical properties of the output medium are known, such as for print layout. E.g.
padding:
20px
;
Unit | Physical property | Conversion | In px |
---|---|---|---|
px |
Pixels. | For low-res displays, equals 1 display pixel (dot). For printers and high-resolution screens, 1 px implies multiple device pixels. |
1 |
cm |
Centermeters | 1cm = 96px/2.54 | ~37.8 |
mm |
Milimeters | 1mm = 96px/25.4 | ~3.8 |
in |
Inches | 1in = 96px | 96 |
pc |
Picas | 1pc = 12pt = 1/6th of 1in | 16 |
pt |
Points | 1pt = 1/72nd of 1in | ~ 1.3 |
- Relative lengths represent size in terms of some other distance. Depending on the unit, this can be the size of a specific character, the line height, or the size of the viewport.
Unit | Description | Example |
---|---|---|
em |
Multiple of base (i.e. parent element's) font-size that is in use. Use when sizing elements in comparison to other elements nearby. |
font-size: 1.25em ; |
rem |
Multiple of root element (i.e. <html> tag) font-size. Use when sizing elements consistently across entire page. |
line-height: 1.6rem ; |
% |
Size element relative to the dimensions of parent element (i.e. container). NB: For padding & margin , the % for all four sides is computed using the width of the parent element. WARNING: If used with box-model, may cause overflow problems |
width: 60% ; |
auto |
The browser will calculate and select a width for the specified element. E.g. If the height property of an image is set to auto, the image's height will automatically scale proportionally with the width. WARNING: auto may be the default or inherited, inwhich case auto appears to do nothing. |
height: auto ; |
ch vh vw vmin vmax |
See <length> for details. |
- NB: When using relative sizing, to create a consistent layout based on text size and text-related dimensions on the page (i.e. padding around text), use
ems
andrems
. Otherwise, percentages should be used.
- A flex container is an element on a page that contains flex items.
- All direct child elements of a flex container are flex items.
- Some of the properties apply to flex containers, while others apply to flex items.
- To designate an element as a flex container, set
display
of element toflex
orinline-flex
- Flex items and containers have the following settable properties;
Property | Axis of effect |
Default | Purpose |
---|---|---|---|
justify-content |
main-axis |
normal (none) |
justify contents along container |
align-items |
cross-axis |
stretch |
Flex-box cross-axis (Gridlayout block-axis ) alignsingle-line (i.e. nowrap) contents. |
flex-grow |
main-axis |
0 (none) |
grow item proportionally to siblings, using parent's extra space |
flex-shrink |
main-axis |
1 |
Shrink item proportionally to siblings, when parent container too small |
flex-basis |
main-axis |
auto |
Set initial size of item |
flex |
main-axis |
N/A | Combines flex-grow , flex-shrink and flex-basis settings |
flex-wrap |
main-axis |
nowrap |
Sets wrapping of contained items, when container has insufficient space |
align-content |
cross-axis |
stretch |
Flex-box cross-axis (Gridlayout block-axis ) alignmulti-line (i.e. with wrapping) contents |
flex-direction |
N/A | row |
Set main-axis and direction |
flex-flow |
N/A | N/A | Combines flex-direction and flex-wrap settings |
Flex-box main-axis
and cross-axis
- The behaviour of many flex-box properties are dependent on the
main-axis
andcross-axis
, which are set by theflex-direction
property. Thecross-axis
is always perpendicular to themain-axis
. - See heading links for diagrams
- Once an element is a flex containter, the default settings for each property applies, and hence it's contents will;
- Have the
main-axis
asrow
(i.e. horizontal and left to right). - On the
main-axis
;- Not stretch
- Not grow if extra space is present
- Shrink if there is not enough space
- Not wrap
- On the
cross-axis
;- Stretch
- Have the
- Flexboxes can be nested.
- Example, with code from course;;
justify-content
: [et al]
- main-axis
justify contents along container
- Distribute space between and around content items along the
main-axis
of their container.
Setting | Effect |
---|---|
flex-start |
Pack flex items from the start |
flex-end |
Pack flex items from the end |
center |
Pack items around the center |
space-around |
Distribute items evenly. Items have a half-size space on either end. |
space-between |
Distribute items evenly. The first item is flush with the start, the last is flush with the end. |
start |
Pack items from the start |
end |
Pack items from the end |
left |
Pack items from the left |
right |
Pack items from the right |
normal (default) |
Pack items in their default position as if no justify-content value was set. |
space-evenly |
Distribute items evenly Items have equal space around them. |
stretch |
Distribute items evenly. Stretch 'auto'-sized items to fit the container. |
safe <setting> |
If the item overflows the alignment container causing data loss, the item is instead aligned as ifthe alignment mode were start. |
unsafe <setting> |
Regardless of the relative sizes of the item and alignment container and whether overflow which causes data loss might happen, the given alignment value is honored. |
- Example, with code from course;;
align-items
: [et al]
- flex-box cross-axis
(gridlayout block-axis
) align single-row contents
- Sets the align-self value on all direct children as a group
- Sets the alignment of an item within its containing block.
- Has no effect on wrapped multiple-line rows
- Can use
align-contents
instead.
- Can use
- Example, with code, from course;;
flex-grow
: [n]
- main-axis
grow item proportionally to siblings, using parent's extra space
- Effect is proportional to flex-grow specified in siblings, with larger proportions taking up more of the partent's extra space
- Default of 0 means items do not grow by default
- Margins are unaffected
- WARNING: Minimum and maximum widths will take precedence over flex-grow
Setting | Effect on cross-axis |
---|---|
Number (default 0) |
Sets flex-grow for item itself (i.e. not it's children). NB: Can be fractions. Can't be negative. |
- Example, with code from course;
flex-shrink
: [n]
- main-axis
shrink item
proportionally to siblings, when parent container too small
- Effect is proportional to flex-shrink specified in siblings, with smaller proportions shrinking more.
- Default of 1 means items will shrink by default.
- Margins are unaffected
- WARNING: Minimum and maximum widths will take precedence over flex-shrink
Setting | Effect on cross-axis |
---|---|
Number (default 1) |
Sets flex-shrink for item itself (i.e. not it's children). NB: Can be fractions. Can't be negative. |
- Example, with code from course;
flex-basis
: [auto | unit ]
- set initial size of item along main-axis
- Set inital size of item before it stretches or shrinks.
- Controls one dimension of item, depending on
flex-direction
setting;- When
flex-direction
: row, controls item'swidth
- When
flex-direction
: column, controls item'sheight
- When
- WARNING:
flex-bais
overrides (i.e. has prioroty over)width
(whenflex-direction
: row) orheight
(whenflex-direction
: column) settings.
Setting | Effect on main-axis |
---|---|
units |
Set inital size of item before it stretches or shrinks. |
auto (default) |
??? |
fill |
|
max-content |
|
min-content |
|
fit-content |
|
content |
Indicates automatic sizing, based on the flex item’s content. |
- Example, with code from course;
flex
: [auto | initial | none | units]
- combines grow, shrink and basis settings on main-axis
Setting | Effect on cross-axis |
Example |
---|---|---|
auto |
Sized according to its width and height properties,but grows to absorb any extra free space in the flex container, and shrinks to its minimum size to fit the container. Equivalent to setting flex: 1 1 auto; . |
flex: auto; |
initial (default) |
Sized according to its width and height properties. It shrinks to its minimum size to fit the container, but does not grow to absorb any extra free space in the flex container. Equivalent to setting flex: 0 1 auto . |
flex: inital; |
none |
Sized according to its width and height properties. It is fully inflexible: it neither shrinks nor grows in relation to the flex container. Equivalent to setting flex: 0 0 auto . |
flex: none; |
1 unitless value | Set flex-grow |
flex: 2; |
1 unit value | Set flex-basis |
flex: 2em; |
2 unitless values | Sets flex-grow , flex-shrink |
flex: 2 1; |
1 unitless value, 1 unit value |
Sets flex-grow , flex-basis |
flex: 2 100px; |
2 unitless values, 1 unit value |
Sets flex-grow , flex-shrink , flex-basis |
flex: 2 2 10%; |
flex-wrap
: [wrap | nowrap | wrap-reverse ]
- sets wrapping of contained items along main-axis
, when container has insufficient space
Setting | Effect on ???-axis |
---|---|
wrap |
When container has insufficient space, move items to the row below |
nowrap (default) |
When container has insufficient space, shrink the items |
wrap-reverse |
When container has insufficient space, move items to the row above |
- Example, with code from course;
align-content
: [et al]
- flex-box cross-axis
(gridlayout block-axis
) align multi-row contents
- Has no effect on single line flex containers (i.e. ones with the default
flex-wrap: nowrap
).- Can use
align-items
with single line flex containers instead.
- Can use
- Sets the align-self value on all direct children as a group
- Sets the alignment of an item within its containing block.
- Example, with code from course;
flex-direction
: [row | row-reverse | column | column-reverse]
- set main-axis
and direction.
-
See here for links to Mozilla docs re:
main-axis
andcross-axis
-
The
main-axis
is used to position flex items with the following properties:- justify-content
- flex-grow
- flex-shrink
- flex-basis
- flex
- flex-wrap
-
The
cross-axis
is used to position flex items with the following properties:- align-items
- align-content
Setting | main-axis and direction |
---|---|
row (default) |
Left to right across the parent element starting from the top left corner (default). |
row-reverse |
Right to left across the parent element starting from the top right corner. |
column |
Top to bottom of the parent element starting from the top left corner. |
column-reverse |
The bottom to the top of the parent element starting from the bottom left |
- Example, with code from course;
flex-flow
: [flex-direction | flex-wrap]
- combines flex-wrap and flex-direction settings
- All values for flex-direction and flex-wrap are accepted.
- Order of arguments is not important
flex-direction settings |
---|
row |
row-reverse |
column |
column-reverse |
flex-wrap settings |
---|
nowrap |
wrap |
wrap-reverse |
color
and background-color
[ keyword #, rgb, hsl, rgba, hsla]
;
Property | Effect |
---|---|
color [ #, rgb, hsl, rgba, hsla] background [ #, rgb, hsl, rgba, hsla] |
Sets element's foreground & backround respectively as per schemes below. |
Setting | Effect |
---|---|
keyword |
See list here. NB: Each color keyword has an equivalent #hex rgb value. |
#hhhhhh |
6 or 3 digit hexadecimal RGB color. 3 digit represents 6 digit where each pair is a double. E.g. #00FFFF = #0FF |
rgb(ddd, ddd, ddd) |
Specifies RGB values as 0-255 decimals |
hsl(ddd, ddd%, ddd%) |
1) 0-360º Hue. As per color wheel. 0/360 = Red, 120 = green, 240 = blue. 2) 0-100% Saturation. Less is toward center of wheel (greyer) and more moves to perimeter (richer) 3) 0-100% Lightness. 50% = normal, 0% = black, 100% = white |
Setting | Effect |
---|---|
rgba(ddd, ddd, ddd, 0-1) hsla(ddd, ddd%, ddd%, 0-1) |
1) The first three arguments specify the color as per rgb & hsl above. 2) Opacity is set by the last real decimal valve. 0.0 = transparent, 1.0 = opaque. |
Setting via opacity
: real-decimal
Property (linked) |
Arguments | Notes |
---|---|---|
font-family |
font-name, fallback-font1, ... , [serif, sans-serif] |
1) If font-name is not available, use fallbacks or system serif/sans-serif. 2) Quote name if name contains spaces. |
font-weight |
bold , normal ,100 -900 in 100's |
400 is usually default, 700 is bold, 300 is light. |
font-style |
italic , normal ,oblique <angle>? |
|
word-spacing |
normal unit |
Default is 0.25em. NB: em unit preferred. |
letter-spacing |
normal unit |
Aka 'kerning'. NB: em unit preferred. |
text-transform |
none capitalize uppercase lowercase full-width |
|
text-align |
left , center , right |
|
line-height |
normal % unit unitless-number |
unitless-number computes the line height as a ratio of the font size. |
See my example of using the below here.
- Search for fonts
- Having found a font, add it and select the variations (e.g. regualr (400) and
- When all are saved, open the bottom-right widget and link or import the font(s);
- Link fonts via index.html;
- Copy-and-paste the provided <link> tag into the <head> tag of index.html. E.g.
<link href="https://fonts.googleapis.com/css?family=Space+Mono" rel="stylesheet">
- Copy-and-paste the provided <link> tag into the <head> tag of index.html. E.g.
- Import @font-face via style.css
- Copy-and-paste the provided <link> tag into a browser.
- From the raw css displayed, copy-and-paste all the
/* latin */
@font-face {...} blocks into the top of style.css.@font-face { font-family: 'Space Mono'; font-style: normal; font-weight: 700; src: local('Space Mono Bold'), local('SpaceMono-Bold'), url(https://fonts.gstatic.com/s/spacemono/v1/vdpMRWfyjfCvDYTz00NEPGaVI6zN22yiurzcBKxPjFE.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; }
- Link fonts via index.html;
- Add font rules to selector
- Copy-and-paste the font rules in to the appropriate selector of style.css.
<some_css_selector> { font-family: "Space Mono", monospace; }
- Download font files from somewhere like fontsquirrel.com, into a suitable location such as ./fonts
- For each font file, add an appropriate @font-face entry into style.css. E.g.;
/* The 2 @font-face below bring in regular and bold versions of the Glegoo font. Note the font-weight's 400 & 700 are required to set them up correctly */ @font-face { font-family: "Glegoo"; font-style: normal; font-weight: 400; src: url(fonts/Glegoo-Regular.ttf) format('truetype'); } @font-face { font-family: "Glegoo"; font-style: normal; font-weight: 700; src: url(fonts/Glegoo-Bold.ttf) format('truetype'); }
Detecting browser information with @media
rules
@media
features can detect many aspects of a user's browser, including the screen's width, height, resolution, orientation- The points at which
@media
queries are set are called breakpoints.
@media only screen and (min-width: 320px) and (max-width: 480px) {...}
@media only screen and (min-width: 480px), (orientation: landscape) {...}
- I'm unclear of precedence - need to read
@media
@media only screen and (min-width: 320px) and (max-width: 480px), (orientation: portrait) { .gallery-item .thumbnail { width: 95%; } }
- The following @media applies rules to browser windows that are upto 480px wide
@media only screen and (max-width: 480px) { body { font-size: 12px; } }
-
The following 2 are valid, equivalent & used in the wild;
- Using 2nd
and
to chain requirements;
@media only screen and (min-width: 320px) and (max-width: 480px) { /* ruleset for 320px - 480px */ }
- Using 2 separate rule sets;
@media only screen and (min-width: 320px) { /* ruleset for 320px - 479px */ } @media only screen and (min-width: 480px) { /* ruleset for > 480px */ }
- Using 2nd
Rules for resolution
DPI in <resolution> units
- Can target high resolution devices. E.g.;
@media only screen and (min-resolution: 150dpi) {
/* CSS for high resolution screens */
}
- NB: A 40" 4K monitor has 96dpi (3840px / 40in = 96dpi)
- WARNING: When Firefox zooms in, the DPI is calculated as higher than the physical display's DPI => to test
resolution
rules, need to check Zoom level has been rest.
Rule for screen orientation
- If the windows
height
is greater than, or equal towidth
, then it is portrait oriented.
@media only screen and (orientation: landscape) {
/* CSS for high resolution screens */
}
@media only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) {
/* CSS for tablets in landscape orientation */
}
- Important: Use these to address layout problems, rather than drive design as per these guidelines.
Use relative units when sizing and positioning
-
Absolute units for sizing and positioning are fixed and prevent responsive websites.
-
Elements that have size units of
rem
are relative to the root font-size and will be modified by changing root element. E.g.;html { font-size: 10px; } h1 { font-size: 2rem; }
-
Elements that have size units of
em
are relative to the base font-size in use, and will be modified when changing the base element. Linking contained element's sizes to the container means they can be sized relatively to one another, which will be maintained if the contained elements as a group are re-sized. E.g.;.supporting { /* "support" element's font size is relative to the root html element */ font-size: 1.1rem; } /* h2 and p element's font sizes are relative to one another */ /* through their "support" container */ .supporting h2 { font-size: 1.8em; } .supporting p { font-size: 1.2em; }
-
Linking element sizes and positions together centralises altering the overall layout. This is very helpful when combined with
@media
.
Use @media
rules to address layout issues
-
Best practice;
- Set breakpoints where the dimensions at which the layout breaks or looks odd, to allow CSS rules to resize the page and reorganize.
- Avoid setting breakpoints based on specific devices.
- Avoid forcing projects around a certain screen size.
- Combine with using relative units.
-
See also Using media queries
- Test (not design) using these common screen sizes;
- Test browser window sizes using the rulers and "Responsive Design Mode" in Firefox.
- WARNING: Sometimes Firefox's inspection information stops dynamically displaying the CSS rules being applied to elements, making it much harder to observe
@media
breakpoints in responsive designs. WORKAROUND this by closing the sites tab/window and re-open the site.
- WARNING: Sometimes Firefox's inspection information stops dynamically displaying the CSS rules being applied to elements, making it much harder to observe
Background images background
In the CSS below, the first CSS declaration sets the background image (# is a placeholder for an image URL in this example). The second declaration instructs the CSS compiler to not repeat the image (by default, images will repeat). The third declaration centers the image within the element.
The third declaration scales the background image to cover the entire background of the element, while keeping the image in proportion. If the dimensions of the image exceed the dimensions of the container then only a portion of the image will display.
body {
background-image: url('#');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
- WARNING:
background-size: cover
may appear to have no effect unless the screen is sufficently wide and/or the zoom level is out far enough. Testing using mobile device emulation may also be needed.
In the CSS below, .container represents a container div. It is set to a width of 50% (half of the browser's width, in this example) and a height of 200 pixels. Setting overflow to hidden ensures that any content with dimensions larger than the container will be hidden from view.
The second CSS rule ensures that images scale with the width of the container. The height property is set to auto, meaning an image's height will automatically scale proportionally with the width. Finally, the last line will display images as block level elements (rather than inline-block, their default state). This will prevent images from attempting to align with other content on the page (like text), which can add unintended margin to the images.
Note: The example above scales the width of an image (or video) to the width of a container. If the image is larger than the container, the vertical portion of the image will overflow and will not display. To swap this behavior, set max-height to 100% and width to auto (essentially swapping the values). This will scale the height of the image with the height of the container instead. If the image is larger than the container, the horizontal portion of the image will overflow and not display.
.container {
width: 50%;
height: 200px;
overflow: hidden;
}
.container img {
max-width: 100%;
height: auto;
display: block;
}
- This tries to minimise browsers creating problems by having diferent user agent default styles.
- The reset.css used in the Codecademy projects in the this reppo seem to be effective, but searching the web may find better.
When working out what declarations are doing;
- View it in a real world sitution, directly in a browser on a machine (rather than in an emulator).
- Have the MDN and W3C spec pages on hand for quick review.
- Zoom in for small devices.
- Zoom out for large displays & maximise window.
- Keep in mind the purpose is fitting the view-port with meaningful, legible, intuitive content and interfaces.
- When learning it can be very useful to isolate a problem or a plan down to a single objective. Then shrink and stretch and bang the living daylights out of the conceptual view. Your machine is that environment. The padded room, so to speak.
- When in doubt, go back to the default style sheet and express the HTML elements using only that. Graduate views when experimenting. Don’t aim for perfection, but effect. If you don’t see it, then it must not be in the declarations.
- In some cases the default or inherited value is the same as what what is being tried, so no change will occur.
- It doesn’t make conceptual sense and is hence contrived, even if it can be made to work.
- Blocks with margins is the way to go on such objects.