CSS Tips

3 Pillars of writing HTML & CSS

Responsive Design, Maintainable & Scalable Code, Web Performance

Reset CSS

*,
a::before,
a::after {
 margin: 0;
 padding: 0;
 box-sizing: inherit;
}

body {
 box-sizing: border-box; // padding are not added to width of box, width size is set at border level
}

Font Sizing, REMs and Responsive text sizing

Bad practice to declare font-size as pixels (prevents users from changing font-size in their browsers). Declaring font-size in REM sizes font to a multiple of the root font size (set by the browser, usually 16px).

If you wish to change the root font size, do so under the html element and as a percentage of the browser root:

html {
 font-size: 87.5%; // 14px if browser root is 16px
}

You can then use media queries to resize all fonts proportionately by changing the size declared in html.

Not supported in IE9.

Scaling divs in relation to Viewport Height:

Use [int]vh; (Integer is percentage of viewport height.

header : 95vh // Header is 95% of height of viewport

Clearfix

<nav class="clearfix">

.clearfix::after {
 content: "";
 clear: both;
 display: table;
}

Gradient

background-image: linear-gradient(to right bottom, rgba1, rgba2), url(../img/hero.jpg);

The above CSS puts an opaque gradient from top left to right bottom over a hero image.

Clip-Path / Polygon

clip-path: polygon(x y, x y, x y, x y, x y)

Creates a clipping mask over the element. Use polygon to create a shape. Parameters are Top-right, top-left, bottom-left, bottom-right.

Use Clippy to generate polygon

Translate (transform)

Reposition the elements top/left co-ordinates. Useful when using absolute position to centre an element:

.element {
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
}

g

jQuery Basics

The document ready function

$(document).ready(function(){
// jQuery programming goes here
}); // end ready

This is only required when you include your javaScript in the head of your document before html – because you often use JS to manipulate existing HTML on the page, you’ll need to wait until all the elements have loaded before executing any JS commands.

Flexbox

Flexbox is a new module in CSS3 that makes it easy to align elements to ne another in different directions and orders.

Gives the container the ability to expand and shrink elements to best use the available space.

Replaces float layouts.

Concepts

Flex Container & Flex Items, Main and Cross Axis

display: flex

Container
flex-direction: row | row-reverse | column | column-reverse

which direction the Main Axis goes (left>right, up or down)

row-reverse inverts item order along main axis

column aligns items on top of each other down the cross axis (column-reverse reverses order)

flex-wrap: nowrap | wrap | wrap-reverse

Defines if the flex items should go to a next line if not enough space

justify-content: flex-start | flex-end | center | space-betweem | space-around | space-evenly

How flex items will be aligned on the main axis:

center: center justified

space-between = fully justified

space-around : space space around each item

space-evenly: similar to above but equal space between each element

flex-end / flex start: right/left justified

align-items: stretch | flex-start | flex-end | center |  baseline

How flex items will be aligned on the cross axis

align-content: stretch | flex-start | flex-end | center | space-between | space-around

Defines how flex items are aligned on the cross axis when there is more than one row.

stretch – resizes all items to size of largest.

center: horizontal alignment of items

flex-start / flex-end: aligns all items to top / bottom of div

baseline:  aligns items by the bottom (baseline) of the text contained on all items horizontally.

Item
align-self: auto | stretch | flex-start | flex-end | center | baseline

Similar to align-items but for single items

order: 0 | <integer>

defines order in one specific item should appear (to reorder)

flex-grow: 0 | <integer>

Maximum width

flex grow: 1 will allow the item to expand as much as possible to take all available space in the container

flex-shrink: 1 | <integer>

minimum width

1: element is allowed to shrink

0: element no longer allowed to shrink

flex-basis: auto | <length>

Base width

Percentage based (only if there is available space)

flex: 0 1 auto

 

 

AJAX with JSON and jQuery

Javascript Object Notation

  • Uses basic JavaScript arrays and objects to store data.
  • Can either be formatted using array or object notation or a combo of both.

JSON objects vs arrays

Creates key/value pairs to help distinguish what data is in the array.

JSON Formatted data

JSON properties must be enclosed in double-quotes.
[
{
"name": "Aimee",
"inOffice": "true",
},
{
"name": "Bob",
"inOffice": "true",
},
{
"name": "Carl",
"inOffice": "false",
},
]

Use a validator like JSONLint to check if the JSON is formatted correctly.

Parsing JSON

JSON data is just a string of text and needs to be converted to JavaScript (parsing). Takes a string and converts it into a JavaScript object.

JSON.parse(xhr.responseText)

Processing JSON

Using JavaScript

var statusHTML = "<ul>";for (var i=0; i < jsonObject.length; i ++) {
statusHTML += "<li>" . jsonObject[i].keyname . "</li>";
}
status HTML += "ul";

Using jQuery

jQuery has a method function that rolls all four steps of a usual AJAX request into one:

function sendAJAX() {
$('#ajax').load(sidebar.html)
}

jQuery has a number of shorthand methods to simplify using AJAX. These are documented on the jQuery API reference website.

The get method

The get method does not require an element to be selected first.

var url = "/employees.html';
The URL you are making the request to. (as you would use in the js Open method)

var data ={firstName : "Dave", lastName : "McFarland"}
In the form of a query string, the data that would be added to the query string appended to the URL

var callback = function(response){
// Do something with the ajax response
}

$.get(url, data, callback);

getJSON method

$.getJSON(url, data, callback);

The data needs to be in JSON format. The method will automatically parse the JSON data returned. Process the response using the jQuery each method.

$.each(array_or_object, callback) ;

$.each(response, function(index, value) {});

post method

$.post(url,data,callback);

$('form').submit(function(evt) {
evt.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize(); //creates a text string with standar URL-encoded notation of fields in an HTML form
$.post(url, formData, function(response{
$('#signup').html(');
});

ajax method

$.ajax(url,settings);

The ultimate (low-level) AJAX method. Requires a url parameter and a JavaScript object containing settings for how the AJAX request should be handled. Refer to the online documentation for all the settings.
$.ajax(url, {
data : formData,
type : "POST",
success : function(response) {
$('#signup").html(<p>Thanks for signing up!</p&gt")
}
});

Handling Errors with jQuery & Ajax

.fail method

A chainable method – jqXHR will return the error.

$.get('missing.html',function(data){ $('#myDiv').html(data); }).fail(function (jqXHR) { alert(jqXHR.statusText)});});

Doesn’t work for a $.load() method and doesn’t work when using JSONP

 

Better to use Fetch API

Ajax – Basics

AJAX stands for Asynchronous Javascript and XML

also knowns as …

XML HTTP Request (XHR)

The AJAX/XHR process consists of the following:

  1. Create an XML HTTP Request object
  2. Create a Callback function
  3. Open a Request
  4. Send the Request (to a webserver)
Creating an xml http request object

This is done by creating an object variable using the XMLHttpRequest() function:

var xhr = new XMLHttpRequest();

Creating a callback function

Create a function that will be called once ready state has changed to status 4:

xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//action
}
};

OPen a request

Use the .open() function:. eg:

xhr.open('GET', 'sidebar.html');

Send the Request

Pass info to send (in the parenthesis) to the server:

xhr.send();


Ready State and Callbacks

Each stage of the process involves a readyState. Each step changes the ready stage of the request. A callback responds to the change in that state

An XML HTTP request object’s readyState property holds a number from 0 to 4. Zero to 3 represents stages from when the object is created to when the response is coming. ReadyState 4 is when the web server has sent everything it’s going to send.

Status Property

The object also returns a status as per the following

200 – 0k

401 – not authorised

404 – not found

500 – database  error

eg. To create a callback when the status is ok. The status has a property of .statusText to provide further info:

if (xhr.status === 200) {

//action

} else {
alert(xhr.statusText);
}

Displaying results

Use the XHR object’s responseText property:
xhr.responseText;