Css Tip – Css Browser Selector

Styling sites for different browsers have always been a headache for front end developers. Sometimes, the implementation has its own prefixes, sometimes the model doesn’t work at all.

Browser specific stylesheets

So developers came up with the idea of browser specific stylesheets. For each different browser, you redefine a few style declarations to make the layout and styling work.

But having multiple stylesheets is far from optimal. You take more effort to organize your files, some browsers have quirks that needs some fixing, and all sorts of weird problem pops up. And that adds up to a lot of time wasted.

Solution

One more elegant solution will be to borrow the idea of browser prefixing. Instead of having multiple stylesheets, you now have one stylesheet with all the fixes that you can apply.

Even better, using this method allows you to extract other details like browser versions and operating systems. This way, you can target differrent content at different platforms and still have a static one-page website.

How it works

This is a script from Rafael Lima. The basic idea is to extract information from the userAgent string and apply the appropriate classes to the document element.

And when defining the style declarations, you just have to use the appropriate classes to fix the different cross browser errors.

Access the script from here

Remarks

This way of frontend development focuses on limiting server side interaction. Sending all the information to the client and let all the decision to be done over the client side.

All methods have their pros and cons. This method will be suitable for simple sites that require simple static content. If you are working on a site with dynamic content, handling the browser fixes server-side could be an appropriate choice, since its just a simple extension and can help reduce page load time.

If there is any questions or queries, leave a comment or drop me an email.

Css Tip – Using flexbox to style a button

When you try to use flexbox in a button, it doesn’t render as it is supposed to , why is this so, and how do I fix this?

Introduction

The flexbox model is one of the up and coming standards for web design. Once you have mastered it, you can use it for any design you want.

You would expect that it should work on different HTML elements as well, but when you try to apply the model to a button and render it in Firefox, it just wouldn’t render properly. (click on caption to view codepen)

How it appears
how it looks like

How it is supposed to look like
how it supposed to look

As a good developer ensuring cross browser compatibility, this problem annoys me to no end.

Solution (inline block)

In the particular example above where we try to style the button, we could render the image and text as inline block. In that case, the image and text will align side by side.

But using this method, you won’t be able to easily get the image and text to align vertically (unless you use some margin or valign hack, which complicate stuff).

The more generic method

I didn’t believe it could work until I tried it out, the solution seems too simple. Apparently, by wrapping the button’s content with a “div” element, you can render the flexbox properly without any problems.

This way, you can still use flexbox for all your layout needs. But do note that having a content wrapper means that you have to remember to remove the background and border of your button to get the look that you want.

Why didn’t it work originally?

It all boils down to how the button is implemented in Firefox. For special elements, like buttons and form inputs, its safer to assume that structured differently across browsers.

This is because these special elements have unique responses that the browser have to take into consideration, so they are often rendered differently cross browser.

If you are searching for a more technical answer, you can use this thread as a starting point.

Any questions or issues, you can leave a comment here, or direct your query to my email.

JavaScript promises

This is just a basic introduction to javascript promises. This is inspired by this article, which explains the intricacies very well.

javascript callbacks

One of the unique feature of javascript is the use of callback functions. Its extremely essential considering the fact that javascript is a single threaded language.

For those that have no idea what I am talking about, here is how callback functions are usually used.

function getData(callback){
    callback(loadDataFromSomewhere());
}

getData(processData);

When the getData is done, the result is passed into processData.

Callbacks are all well and good, until you start working on some complicated API project and all hell break loose. If you have been working with callbacks for a while now, you would probably have heard the term “pyramid of doom”, where your function calls stretches all the way to the right.

But there are more to [promises] than nice looking code. Using callbacks deprives us of basic programming features such as return and throw. More importantly, when something is wrong, there is no way to track down where that mistake is. All these results in bad code design.

Javascript promises

Promise, as defined by the A+ spec, is like an upgraded version of callback functions.

For most modern browsers, promises are implemented as window.Promise, but for those who are looking good polyfill, is one option you can look at.

Basic functions (then & catch)

If you use promises, there is two things you cannot do without, the functions then and catch. This knowledge should be sufficient to use most promise-based library (eg. pouchdb).

The function then accepts 2 parameters, the first is the function that the data is passed into if everything goes well, the second is triggered when some error has occured.

As for catch, it’s just a shortcut to write then(null, function). So when an error is thrown, the error object is passed into the function.

The promise stack

You can use promises as callback functions, but there is a much nicer way to format your code.

remotedb.allDocs(...).then(function (resultOfAllDocs) {
    return localdb.put(...);
}).then(function (resultOfPut) {
    return localdb.get(...);
}).then(function (resultOfGet) {
    return localdb.put(...);
}).catch(function (err) {
    console.log(err);
});

There is one special feature about promises. If you return a promise in the function, the result is passed into the next then function. This way, you can chain different sections of code together. (The allDocs, then the put, then the get).

The catch function at the end is a good practice. Putting it at the end ensures that whenever an error is thrown, it will be caught. Regardless of which level the error occurs, the error will still be logged.

Advanced functions (resolve & reject)

When you create your own library using promises, you tend to face the need to wrap your synchronous code as asynchronous code. Here is where resolve comes in.

function someAPI(){
    return Promise.resolve().then(function(){
        // some error might be thrown here
        return 'someSynchronousValue';    
    }).then(/* ... */);
}

This way, all your code will be promise-y, even the simple functions. This ensures code design consistency.

Besides, when you use promises this way, you can catch error easily. Gone are the days of slow and inefficient debugging.

So what about reject? The reject function returns a promise that is rejected immediately.

new Promise().resolve('some value').then(function(val){
    // do something to val
});

new Promise().reject(new Error('some error')).then(function(val){
   // do something to val
   // but this function will be skipped
}).catch(function(e){
    // this function is called immediately    
});

Promise.all (The foreach in promises)

There is another use case for promises. Let’s say we have a database query that returns a few rows, and we wanna update those rows. Typically, this is what the code will look like (in the minds of those non-promise ninjas).

getAllRows().then(function(result){
    result.rows.forEach(function(row){
        // update value of row
        row.val += 1;
        updateRow(row);              
    });
}).then(function () {
    // Naively believe all docs have been updated now!
});

But here is the right way to do it, with Promise.all of course.

getAllRows().then(function(result){
    return Promise.all(result.rows.map(function(row){
        //update value of row
        row.val += 1;
        return updateRow(row);
    }));
}).then(function(arrayOfUpdateRowResults){
    // all docs have been updated    
});

End

Well, all these are just the basics of using promises, there are certainly alot more to learn. If you are interested, I implore you to give this article a read. You will learn much much more.

Getting Started 3: HTML – forms and tables

This is the 3rd post in the Getting Started series.

In this post, I will be introducing more HTML elements, mainly the form and table elements.

HTML forms

For forms, the two main attribute are action and method. action tells the form where to submit the values, and method tells the form how to sumbit the form, the value can be either GET (default) or POST. If you have no idea what I am rambling about, read the rest first, then head over to this article to get it all sorted out.

What’s more important here is the form elements. These comprises everything that makes up a form. When rendered, the browser will display the form with the different field, depending on the element used.

Each element will have the tag name and it would correspond to the different fields in the form (eg. ’email’ and ‘password’ for a login form).

input (the fundamental one)

This is the one you probably will use the most often. The input element is usually accompanied by a type tag. For those usual text input that you see on most forms, the type value is text, but there are other types of inputs too, like number and date, just to name a few.

One commonly used input will be the password typed input. Instead of displaying the text, asterixs are used instead to hide the input text from prying eyes.

Most input type will also have the placeHolder attribute. For modern browsers, the placeHolder value will be displayed when the value of the input is empty.

input (the special kind)

There are some special kinds of input too. When the input is typed submit, a button will be rendered to submit the form where the input resides in.

There is also a type hidden for input tags. This tag will not be displayed and is usually used to submit “behind-the-scene” information that users do not need to enter directly.

textarea (the bigger text input)

For form inputs which are longer (eg. addresses, paragraph of text), there is the textarea element. This element allows for multiline text input. For long input, the textarea is usually used.

option (the dropdown list)

In some inputs you only want to give your users a few options (their month of birth for example).

So you make use of option and select to create the dropdown list they can choose from. select is the tag that encloses the different options, in the aptly named tag, option.

radio buttons (choosing between options)

This is another way of allowing your users to choose from different options. When using radio buttons, all the options are shown, as compared to dropdown lists, where the options are revealed only after a click. Radio buttons are displayed when input are typed radio and are activated when the attribute checked exist for the element.

checkbox (either on or off)

For this element, it used for fields where there is only two choices (eg. ‘remember password’ for a login form) — selected or not. A checkbox is displayed when an input is typed checkbox.

HTML5 inputs (specialized pickers)

As I mentioned before, the input tag is the mother of all inputs. In HTML5, there are some new types of inputs that triggers specialized pickers for choosing (eg. colors, dates). There is really too many types to go through throughly here. Visit this article to view the kinds of input available for use.

input (the expansion pack)

Of course, everything is flexible in frontend development. With sufficient knowledge in styling and javascript, almost everything is possible.

Libraries such as AnyPicker and jqueryUI extends the form functionality of existing browsers by providing even more specialized pickers for different form fields. Anyone interested should go and check them out.

sample (basic HTML forms)

<form>
    <input name='input_text' type='text' placeHolder='text input' />
    <input name='input_hidden' type='hidden' value='not_be_shown' />
    <textarea name='input_textarea' placeHolder='textarea'></textarea>

    <select name='input_select'>
        <option>Option 1</option>
        <option>Option 2</option>
    </select>

    <div class="'radio'">
        <div>
             Option 1
        </div>
        <div>     
            Option 2
        </div>
    </div>

    <div>

        Yes or No
    </div>

    <input type='submit' value='Click Me' />
</form>

rendered:

tables (displaying information)

Most data are displayed in tabular format, it allows the users to quickly see the relation between the different entities and compare data more efficiently.

The tables in HTML are enclosed in the table tags. Within the section, all the information will be formatted by its row and column.

tr & td (basic table elements)

For tables, the most important thing will be the rows and columns. In HTML, the rows are represented using the tr tag and the column, using td tag.

thead and tbody (table styling)

When displaying data, the headings are very important. In HTML, the headings and the data itself is separated using the thead and tbody tags. This way, the headings can be styled separately from the rest of the table.

additional data formatting

Sometimes, tables are not as simple as they seem. In more complex arrangement, a single table cell could span over multiple rows or columns, and this is where colspan and rowspan comes in. Read this article to have a better understand of how to use those attributes.

sample (basic HTML tables)

<table>
    <thead>
        <tr>
            <td>Index</td>
            <td>Name</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>01</td>
            <td>Metta Ong</td>
        </tr>
        <tr>
            <td>02</td>
            <td>Alex Malcolm</td>
        </tr>
    <tbody>
</table>

rendered:

end

Now, here is the end to the third part of the get started tutorial series. In the next few tutorials, you will be working on CSS styling and JavaScript coding.

Getting Started Series

The Getting Started series introduces you to fontend development. Follow these tutorials to learn the basics of web developement. With all these basics, you can make simple adjustments to your sites, add in new information on your own.

  1. Markdown – Simple formatting for documents
  2. HTML – markup language for the web
  3. HTML – forms and tables

But if you want a more complete tutorial, on how to design and implement a website design from scratch, contact ongspxm@gmail.com for more information.

Getting Started 2: html – markup language for web documents

This is the 2nd post in the Getting Started series.

Basic HTML

HTML(hyper text markup language) is a data representation format based on XML. It is used for formatting web documents in general, and contain all the required elements for a browser to render the tags as a website.

Basic XML

HTML(or XML in general) follows this following set of formatting and rules.

Sample XML Document (Not HTML btw)

<Document>
    <title>Hello World Page</title>
    <article author="Metta Ong">Lorem Ipsum</article>
</Document>

As seen from above, the document is formed by tags in the form of tags. Tags come in pairs, opening and closing tags. The opening tag is enclosed with a less than and greater than sign, and a closing tag has a / before the tag name.

Attributes are “descriptions” attached to the tags. In the above example, the author="Metta Ong" is the attribute attached to the article tag. Content placed between the open and close tags are actual text content of the tags.

XML hierachy is pretty simple to understand. In the example above, both the title and article tags are considered children of the Document root tag.


Main structure of web pages

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
    </body>
</html>

Main structure of web document

Different versions of HTML

There are many HTML versions out there (the most recent one is HTML5). To tell the browser which version of HTML your document is, we use the DOCTYPE tag.

So, at the top of your document, incude the following line: “. This tells the browser that your document follows the HTML5 format.

For those curious few out there, there are a few different types of DOCTYPE for HTML4 document is – strict(), transitional(), etc. You can read more about doctypes here.

Main 2 components

The head tag is the place where all the information goes. Data contained in this tag is usually not rendered. By convention, all scripts and styling goes here, together with all the information of the document, like the title, description, etc.

The body tag is the place where all the rendered information go. All your headers, navigation and content goes here.

Document information

<head>
    <title>Title of Document</title>
    <link href='/path/to/stylesheet.css' type='stylesheet' />
</head>

Example head tag

All the information will be stored here, the title of the document, all the metadata (description, author, etc). The metadata can be used for search engine optimization (SEO), it gives the browser detailed information to categorize your document (more on that in other tutorial).

While styling can be done on the main html file itself, you can also attach stylesheets using the link tag. The syntax to do so is as follows: “

You can attach things like favicons (the small tiny logos for your page). Using the link tags, these images can be attached as so:

<!-- linking a style sheet -->
<link href='path/to/style.css' rel='stylesheet' />

<!-- favicon -->
<link href='path/to/icon.png' rel='icon' type='image/png' />

Basic components

In the previous post, you learnt about formatting documents using markdown, know that you know the basics about document formatting, I will now teach you how to do all that in HTML (yeah, finally :>)

Headers

In markdown, there are different kinds of headers, representing different layers of information. The highest level of all headers have the h1 tag, it all goes all the way, from h2, h3, all the way to h6.

<h1>Usually for the main title of the page.</h1>
<h2>Subheadings. Title for the different sections</h2>
<h3>Even smaller headings, content headers maybe?</h3>
<h4>Not too sure why you would go so deep...</h4>
<h5>Probably just use this for styling purposes...</h5>
<h6>When you reach here, its time to split your content...</h6>

Paragraph text

The p tag (yeah, p for paragraph) used to contain all your text. It can be can be any kind of text, its the generic text container. It is to be embedded in the new HTML5 content tags for SEO (searc engine optimization).

Text styling

Within the paragraph tags, there are some special styling tags to basic transformation to yout text. Here are some of the basic tags available for use.

<b>bold, b for bold</b>
<strong>makes the text bold</strong>

<i>italics effect, i for italics</i>
<em>also italics effect, emphasized</em>

<u>underlined text, u for underline</u>

<mark>highlight text. yep, like a highlighter.</mark>

<s>to show cancellalation (strikethrough), really...</s>
<del>strikethough, similar to the 's' tag</del>

<sub>subscript, text written close to the foot of the text</sub>
<sup>superscript, you know like in math, the power function</sup>

<code>Shows code. text will be displayed in monotype font.</code>

For more advanced styling, you can take a look at the CSS declaration specified for text..

Images

Your pages will be boring with any visual candy. The image tags (img) contains your images. (like duh.)

<img src='http://lorempixel.com/400/200/' alt='a random image' />

Yes, img tags are one of those special kinds that do not need to be closed (because your browser most likely wont render anything enclosed by those tags).

Links

The web works like a interwoven collection of pages, and linking them together will be these a tags (a for anchor). These tags have an attribute href (hyperlink reference), which points to the location you want to redirect your readers to. And this is how you use it:

<a href='http://www.google.com' target='_blank'>
    Link to google
    <img src='path/to/img'/>
</a>

Yep, you can put images in your a tags too. Actually, you can put in anything basic tags under the sun and it will work.


Adding more structure

Most pages will have a certain page structure to it, header,content, footer, at least. The basic containers for most elements are the div and span tags.

But in html5, there are many more tags that can better segmentalized your page into the appropriate sections.

Basic containers

The most basic tags are the div and span. There are a few difference between them. div is for block elements and span is for inline elements.

Block elements refers to a whole section of the page which are displayed as blocks of content. These usually refer to section of the page, such as header, navigation bar or footer.

Inline elements as their names suggest, refers to a small portion of content, within a block to which specialized styling (usually through CSS) is applied to.

HTML5 section tags

In HTML5, there are much more section tags that helps add structure to the documents.

header is a section tag for containing the header content. It can include your logo, your page header, and whatever you plan on putting in your header section.

footer serves the same function as the header tag, a container for footer content (including copyright and contact information).

article contains the main content for the document. But if they are sections in the article, you can use the section tag to separate your content.

nav tags are for navigation. It will consist the links to the different sections of your website (home, about, etc).

aside tags are for sidebars which contain additional bits of information (description for blogs for example).

There are more of course, you can view all that here.


Special Content

In HTML5, there are many new semantics tags added to give structure to your documents.

Pre VS Code

We talk about the code tag just now. But for whole sections of codes, we use the pre tag to contain whole sections of code, preserving the newlines and whitespaces, keeping all the indentation intact.

<pre>
function add(x, y){
    return x+y;
}
</pre>

Figure

The figure tag is used to contain illustrations and pictures. The figcaption is used to add description to the figure. This all is written in the following manner:

<figure>
    <img src='http://lorempixel.com/400/200/' />
    <figcaption>
        Some random picture from lorempixel
    </figcaption>
</figure>

Audio

The audio tag is used to embed an audio resource into the page.

<audio src='test.mp3' type='audio/mpeg' />

Video

video tag is similar to audio tag, but with videos instead of audio files.

Canvas & SVG

The canvas and svg tags are used for drawing things on the page. The canvas tag is controlled using javascript. The svg tag draws using xml. Learn more about canvas and svg.


What’s next

  • Forms (text input, form submission)
  • Tables (systematic display of info)
  • Separators (line breaks)

Getting Started 1: Markdown – Simple formatting for your documents

This will be the first post of a series where I teach frontend developement. This series will include everything you need to know, sufficient to get you started with the basic tools that can help you create your site.

All web pages have formatted structure and content. Markdown exposes the most commonly used structures in web documents, so you can produce web documents without any knowledge of HTML.

Markdown is a widely adopted tool, and can be used to write your posts on WordPress and Tumblr, among other places. It is great place to start gaining more control over your content.

Trying it out

You can try Markdown using a web markdown editor, such as dillinger.io. But for those with more time on their hands, you can download the official markdown compiler to generate your web document (instructions here).

Basic markdown syntax

Here are a few basic formatting that you will be using very often in your documents.

# H1 Header: Title of the document
## H2 Header: Subtitle of the document
### H3 Header: Sub-subtitle of the document
#### H4 Header: It goes all the way to H6, so…
Do remember the space after the hashes

– Unordered list item1
* Unordered list item2
+ Unordered list item3
Yep, you can use either "-", "*" or "+"

1. Ordered list item1
2. Ordered list item2
5. Ordered list item3
It doesn't matter the order of items, they will all appear in the same list.

**Bold Text**
__This is bold text too__
These will be surround by <strong> tags (more on that in the next tutorials).

*Italics Text*
_This works too_
Surrounded in <em> tags, it means emphasised text (we'll cover that later too).

> quoteblock
> > Yep, quoteblocks can be nested
Quoteblocks are separated blocks of text that can be styled different from the rest of the text.

`inline code`
“ If you want to put "`" in your code, this is the way to go. Do note the space after the double backticks. “


***
Horizontal rule (one line across the document), both works

Links and Images

Links and images can be written differently, either inline or referenced.

Inline format for links
[Link Text](Link URL)
[Google](http://www.google.com)

Inline format for images
![Alt text for image](Link to image)
![Example Image](http://path/to/image.jpg)

Reference style format
[Google][1]
[1]: http://www.google.com (optional title)

Self referring format
[Google][]
[google]: http://www.google.com (name not case sensitive)

The references can be placed anywhere in the document, after the paragraph they are used, or at the end of the document, like footnotes.

Where to go after this

Markdown is just a basic formatting for your documents. All these are compiled into HTML(hyper-text markup language) which when viewed in browsers, comes will all the appropriate styling.

In the next tutorial, we will delve deeper into HTML itself, which gives you a better understandin of the HTML file that Markdown outputs.

I want more

There are many different markup languages, geared towards different usages. Personally, I would recommend you to learn and master GitHub Flavoured Markdown. It is one of the few widely adopted extension for markdown and can be used in many blogging and content creation platforms (dillinger supports GFM too).

The extended Github Flavoured Markdown includes many syntax to format more complex document structures like tables, code blocks, and many more.

Fountain is a markup language specially designed for writing scripts for plays. There are many different formatting for standard elements in plays, such as the setting, dialog, etc.

There are more of course, so, go forth and explore them on your own.