Sections: Design, Layout, Animation, Mechanics, Problem solving
- ...media queries, flexible grids, and responsive images to create a user experience that flexes and changes based on a multitude of factors. Like a single ball growing or shrinking to fit through several different hoops.
- Adaptive design is more like the modern definition of progressive enhancement. Instead of one flexible design, adaptive design detects the device and other features and then provides the appropriate feature and layout based on a predefined set of viewport sizes and other characteristics. The site detects the type of device used and delivers the pre-set layout for that device. Instead of a single ball going through several different-sized hoops, you'd have several different balls to use depending on the hoop size.
- Mobile-First Design (introduced by Luke Wroblewski) is an approach that prioritizes the mobile version of a website that should take into account the constraints and user browsing behavior on mobile devices.
- The mobile-first approach is a tenet of progressive enhancement. It is the ideology that mobile design, as the hardest, should be done first. Once the mobile design questions are answered, designing for other devices will be easier.
- What it boils down to is that, the smallest of the designs will have only the essential features, so right away you have designed the heart of your UX.
- The opposite approach is graceful degradation. This incorporates all of the complexities right from the start, then strips them away later for smaller devices.
- The problem with graceful degradation is that when you build the all-inclusive design right from the start, the core and supplementary elements merge and become harder to distinguish and separate. The entire philosophy runs the risk of treating mobile design as more of an afterthought since you’re “cutting down” the experience.
- Mobile Design
display property? What are some ways it can be used?none- Does not display an element (the element no longer affects the layout of the document).
- All child element are also no longer displayed. The document is rendered as if the element did not exist in the document tree
block- The element consumes the whole line in the block direction (which is usually horizontal)
inline- Elements can be laid out beside each other
inline-block- Similar to
inline, but allows some block properties like settingwidthandheight
table- Behaves like the
<table>element
table-row- Behaves like the
<tr>element
table-cell- Behaves like the
<td>element
list-item- Behaves like a
<li>element which allows it to define list-style-type and list-style-position
Resetting vs Normalizing CSS- For example,
margins,paddings,font-sizes of all elements are reset to be the same. You will have to redeclare styling for common typographic elements.
- It also corrects bugs for common browser dependencies.
Resetting is useful for designs that have very customized or unconventional sites
block vs inline-block vs inlineblock - inherits from parent
- starts on a new line and does not allow adjacent HTML elements next to it
-
true
false
- Respected
-
-
inline-block - Depends on content
- Flows along with other content + allows other elements beside it.
-
true
-
true
- Respected
-
-
inline- Depends on content
- Flows along with other content + allows other elements beside it.
false
true
- Only horizontal sides respected.
- Becomes like a block element where you can set vertical margins and padding.
relative vs fixed vs absolute vs static -ally positioned elementsA positioned element is an element whose computed position property is either relative, absolute, fixed or sticky.
static- The default position; the element will flow into the page as it normally would.
- The
top,right,bottom,leftandz-indexproperties do not apply.
relative- The element's position is adjusted relative to itself, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned).
absolute- The element is removed from the flow of the page and positioned at a specified position relative to its closest positioned ancestor if any, or otherwise relative to the initial containing block.
- Absolutely positioned boxes can have margins, and they do not collapse with any other margins.
- These elements do not affect the position of other elements.
fixed- The element is removed from the flow of the page and positioned at a specified position relative to the viewport and doesn't move when scrolled.
sticky - Sticky positioning is a hybrid of relative and fixed positioning.
- The element is treated as
relativepositioned until it crosses a specified threshold, at which point it is treated asfixedpositioned.
z-index property? And what is stacking context and how is it formed?z-index CSS sets the vertical stacking order of positioned elements (or elements that have a position value which is not static)z-index will get stacked on top with a single stacking context-
<span style="z-index:5">top box</span>goes on top of -
<span style="z-index:2">middle box</span>which goes on top of <span style="z-index:auto">auto box</span>
- The stacking context is a three-dimensional conceptualization of HTML elements along an imaginary
z-axisrelative to the user, who is assumed to be facing the viewport or the webpage. HTML elements occupy this space in priority order based on element attributes. - Additionally,
- Stacking contexts can be contained in other stacking contexts, and together create a hierarchy of stacking contexts.
- Each stacking context is completely independent of its siblings: only descendant elements are considered when stacking is processed.
- Each stacking context is self-contained: after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context.
translate() over absolute + relative + fixed positioning ?- When an HTML element is given a
relative,absolute, orfixedpositioning attribute, you’ll be able to move them around by altering it’stop,right,left,bottomattributes. - Similarly, you can use the
translate()method to apply transformations
div {
position: absolute || relative || fixed;
top || bottom || left || right: <length> || <percentage> || auto || inherit;
}div {
transform: translate( <length> || <percentage>, <length> || <percentage>);
}- Performance
- Animating positioned elements will trigger the browser to synchronously recalculate the style and layout*. This is also called
refloworlayout thrashing, and is common performance bottleneck. - User Experience (i.e. silky smooth animations)
top: 2px;➡️top: 3px;➡️top: 4px;➡️top: 5px;translate: 0.1px;➡️translate: 0.2px;➡️translate: 0.3px;➡️translate: 0.4px;➡️translate: 0.5px;➡️translate: 0.6px;➡️translate: 0.7px;➡️translate: 0.8px;➡️translate: 0.9px;➡️translate: 1px;
translate() causes the browser to create a GPU layer for the element, which allows subpixel animation, creating for a smoother position: absolute; top: 2px; to move to position: absolute; top: 5px;, browsers will render the animation pixel by pixel:translate() your browser would render the animation a lot smoother:float vs clearfloatfloatis a positioning property, which can have the values ofleft,right,noneandinherit.
float property applied remain a part of the flow of the web page. - distinctly different absolutely positioned page elements, which are removed from the flow of the webpage
clearclearis also a positioning property ("the sister property of float"), which can have the values ofboth,left,right, andnone- HTML elements with the CSS
clearproperty applied will not move up adjacent to the float, but will move itself down past the float.
clearfix- If a parent element contains nothing but floated elements, its height will be collapsed to nothing. It can be fixed by clearing the float after the floated elements in the container but before the close of the container.
- "The
.clearfixhack" uses a clever CSS pseudo selector (:after) to clear floats. Rather than setting the overflow on the parent, you apply an additional class like.clearfixto it. Then apply this CSS:
.clearfix:after {
content: '.';
visibility: hidden;
display: block;
height: 0;
clear: both;
}- float
- clear
#footer {
clear: both;
}- A block formatting context is a part of a visual CSS rendering of a web page. It's the region in which the layout of block boxes occurs and in which floats interact with other elements.
- Floats, absolutely positioned elements,
inline-blocks,table-cells,table-captions, and elements with overflow other than visible (except when that value has been propagated to the viewport) establish new block formatting contexts.
float) and clearing (see clear) of floats. - The rules for positioning and clearing of floats apply only to things within the same block formatting context.
- Floats don't affect the layout of the content inside other block formatting contexts, and clear only clears past floats in the same block formatting context. Margin collapsing also occurs only between blocks that belong to the same block formatting context.
- The value of
floatis notnone. - The value of
positionis neitherstaticnorrelative. - The value of
displayistable-cell,table-caption,inline-block,flex, orinline-flex. - The value of
overflowis notvisible.
every element in web design is a rectangular box.
box-sizing: content-box (default):The Box Model describes how the padding, border, and margin are added to the content to create this rectangle. In other words, we can say that every box has a content area and an optional surrounding margin, padding, and border.
- The area where your content is displayed. The
widthandheightof this area depends on the element’s content (text, images, videos and any child elements ), and can also be set with thewidthandheightproperties
- The padding sits around the content as white space; its size can be controlled using
paddingand related properties. - If there is no padding width defined, the padding edge is equal to the content edge.
- The border box wraps the content and any padding. Its size and style can be controlled using
borderand related properties. - If there is no border width defined, the border edge is equal to the padding edge.
- The margin is the outermost layer, wrapping the content, padding and border as whitespace between this box and other elements. Its size can be controlled using
marginand related properties. - If there is no margin width defined, the margin edge is equal to the border edge.
Total Width = width + padding-left + padding-right + border-left + border-right + margin-left + margin-right
Total Height = height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom
box-sizing: border-box ("the alternative CSS box model")- The total
widthandheightof the box is explicit. - I.O.W: The
widthandheightaccounts for any border, padding, and margin — and should be deducted to find the dimensions of thecontent-box
.box {
border: 5px solid rebeccapurple;
background-color: lightgray;
padding: 40px;
margin: 40px;
width: 300px;
height: 150px;
}
.alternate {
box-sizing: border-box;
width: 390px;
height: 240px
}The CSS Grid Layout (aka “Grid”) module, is a two-dimensional grid-based layout system. The Grid Layout applies CSS rules both to a parent element (which becomes the Grid Container) and to that element’s children (which become Grid Items).
The CSS Flexbox Layout (Flexible Box) module, is a way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic (thus the word “flex”).
Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element.
When calculating specificity,
- inline style attribute ⇒ 1,0,0,0 points ===1000 points (note: automatic win)
- for each
#id⇒ 0,1,0,0 points === 100 points - for each
.class⇒ 0,0,1,0 === 10 points - for each
<tag>element reference (likep) ⇒ 0,0,0,1 point === 1 point
!important. But not recommendedp {
color: red !important;
}
#thing {
color: green;
}<p id="thing">Will be RED.</p>A CSS preprocessor is a program that lets you generate CSS from the preprocessor's own unique syntax.
- Nest your CSS properties within multiple sets of {} brackets. This makes your CSS code a bit more clean-looking and more intuitive.
- Standard CSS has variable definitions. So what’s the deal? You can do a lot more with Sass variables: iterate them via a for-loop and generate property values dynamically. You can embed them into CSS property names themselves. It’s useful for property-name-N { … } definitions.
- You can add, subtract, multiply and divide CSS values. Sure the original CSS implements this via
calc()but in Sass you don’t have to usecalc()and the implementation is slightly more intuitive.
- Sass lets you create CSS definitions as reusable functions. Speaking of which…
- Among many of its basic features (+, -, *, /), SCSS allows you to write your own functions.
- You can write your own sine and cosine (trigonometry) functions entirely using just the Sass/SCSS syntax just like you would in other languages such as JavaScript.
- Some trigonometry knowledge will be required. But basically, think of sine and cosine as mathematical values that help us calculate the motion of circular progress bars or create animated wave effects, for example.
- You can write CSS using familiar code-flow and control statements such as
for-loops,while-loops,if-elsestatements similar to another languages. But don’t be fooled, Sass still results in standard CSS in the end. It only controls how property and values are generated. It’s not a real-time language. Only a pre-processor.
- Create a set of CSS properties once and reuse them or “mix” together with any new definitions. In practice, you can use mixins to create separate themes for the same layout, for example.
Media queries are useful when you want to modify your site or app depending on a device's general type (such as print vs. screen) or specific characteristics and parameters (such as screen resolution or browser viewport width).
- CSS sprites combine multiple images into one single larger image. It is a commonly-used technique for icons (Gmail uses it).
- Use a sprite generator that packs multiple images into one and generate the appropriate CSS for it.
- Each image would have a corresponding CSS class with
background-image,background-positionandbackground-sizeproperties defined. - To use that image, add the corresponding class to your element.
- Reduce the number of HTTP requests for multiple images (only one single request is required per spritesheet). But with HTTP2, loading multiple images is no longer much of an issue.
- Advance downloading of assets that won't be downloaded until needed, such as images that only appear upon
:hoverpseudo-states. Blinking wouldn't be seen.
- Further reading
- The practice of building an application for modern browsers while ensuring it remains functional in older browsers.
- The practice of building an application for a base level of user experience, but adding functional enhancements when a browser supports it.
- Feature detection using Modernizr.
- Use CSS Feature queries @support
- After identifying the issue and the offending browser, use a separate style sheet that only loads when that specific browser is being used. This technique requires server-side rendering though.
- Use libraries like Bootstrap that already handles these styling issues for you.
- Use
autoprefixerto automatically add vendor prefixes to your code. - Use Reset CSS or Normalize.css.
If a parent element contains nothing but floated elements, its height will be collapsed to nothing. It can be fixed by clearing the float after the floated elements in the container but before the close of the container.
- The empty div method is quite literally, an empty div.
<div style="clear: both;"></div>. - You can also use a
<br />element or some other element used, but div is the most common because... - it has no browser default styling,
- doesn't have any special function, and
- is unlikely to be generically styled with CSS.
- The overflow method relies on setting the overflow CSS property on a parent element.
- If this property is set to
autoorhiddenon the parent element, the parent will expand to contain the floats, effectively clearing it for succeeding elements.
- "The
.clearfixhack" uses a clever CSS pseudo selector (:after) to clear floats. Rather than setting the overflow on the parent, you apply an additional class like.clearfixto it. Then apply this CSS:
.clearfix:after {
content: '.';
visibility: hidden;
display: block;
height: 0;
clear: both;
}Different scenarios call for different float clearing methods. Take for example a grid of blocks, each of different types.
- We could use either the overflow or easy clearing method if each of the color groups had a parent element.
- Or, we use the empty div method in between each group. Three wrapping divs that didn’t previously exist or three after divs that didn’t previously exist. I’ll let you decide which is better.
@media types other than screen?Media types describe the general category of a given device, and there are four types of @media properties (including screen):
all- for all media type devicesprint- for printersspeech- for screenreaders that "reads" the page out loudscreen- for computer screens, tablets, smart-phones etc.
Here is an example of CSS targeting printers:
printmedia type's usage:
@media print {
body {
color: black;
}
}width: 0; height: 0. Make the element not take up any space on the screen at all, resulting in not showing it.position: absolute; left: -99999px. Position it outside of the screen.text-indent: -9999px. This only works on text within theblockelements.
- Why?
- How would the browser parse
#id .class > ul a? - In this example, the key selector is
a. - First, the browser finds all elements matching the key selector
a - Then, the browser finds all
ulelements on the page - Then filters the
aelements down to just those elements that are descendants ofulelements — and so on until it reaches the leftmost selector.
- Try to avoid writing CSS that trigger reflow, repaint, and compositing.
- This is related to: Why
translate()overabsolute positioning - Follow
Block, element, modifier(BEM — Block Element Modifier ) methodology
- 👍 Additional functionality (nested rules, variables, additional functions, trigonometry, control flow / loops / etc., mixins)
- 👍 Facilitates maintainability by enabling DRY via additional functionality
- 👎 Set up, and re-compilation can be slow
col-{n} / 12 ratio of the container.em and rem units?+ and ~ sibling selectors?.