IDs are Unique – But Why?

Ever since I started using CSS experienced programmers came to me saying my use of IDs was bad practice. But everyone so far has failed in giving me a good explanation of why. And it is very difficult for me to follow someone’s advice because of the “well, because IDs are unique” and “because I said so” reason.

Most recently I ran into the issue again when I drafting a landing page for my company recently and one of our frontenders told me that I used too many IDs which is bad practice. I still missed a solid answer to my childish – “but why?”. So this is when I decided to do my own research and after 2 or 3 nights of searching and reading I discovered not only one, but 4 explanations for creating unique IDs (meaning to have only one element on the page marked with that ID).

1. HTML Specs

One of the sites I was linked to revealed the HTML Documentation from W3C. This looks as intimidating and tiring as any other guideline, but it’s actually one of the most important documents to read and understand. If you know the specs you know how you can program your website as clean and as easy to understand for a browser as possible. And it’s clearly marked that

id = name[CS]

This attribute assigns a name to an element. This name must be unique in a document.

If you disobey the specs set in the documentation worst thing that can happen is that the browser won’t display your page correctly. And you know how all of the programmers love debugging…

The Documentation is for HTML4. The HTML5 documentation emphasises on IDs as unique identifiers for elements.

2. Change HTML with JavaScript

Another good reason to not use one ID for multiple Elements is that you can change the text of a document with javascript using the element’s ID. Now I still have to figure out how that works specifically and why I want to change a text with javascript instead of just changing the text inside the HTML, but I guess that will come in handy once you program dynamic websites and not just boring static ones like I do.

3. Use IDs to Create Anchor Tags

IDs can be used to link to a specific section of a page. Now if there are two or more elements on a page with the same ID – how should the browser know which one to link to ?

4. Specificity

Another good reason why you should be careful using IDs when styling a website comes in the biggest tongue twister in coding history (my coding history) – specificity.

Styles in CSS are differently weighted. Rules that are applied later in the document are applied first on the page: When you first define

div {
color: grey;}

and later in the css document

div {
color: green;}

the divs in the document will be green, not grey. So far so easy (why would someone style the same element differently anyways?).

Another way browsers weight CSS when displaying a page is by the position of the CSS itself. Inline CSS has the highest priority, followed by internal stylesheets, after that it will look into external stylesheets and if there are still some rules left to apply it will use the browser default settings.

And then there is specificity of CSS attributes and tags. And in terms of specificity, the ID attribute wins almost every battle. Specificity might not only be the biggest tongue twister, but also the most difficult to understand. Personally I like the explanation of specificity on CSS-Tricks the most. If you use the ID attribute you should be aware that it can override other styling elements which prevents your code from being displayed as you wish.

Very briefly summarised the specificity from elements is as follows: !important > Inline Styling > ID > Class > Element Reference.

While I’m still struggling to understand how exactly I should style a web page and what to consider when using which styling rule, I do understand what IDs are and why they should be applied carefully (and once per element per page!). I found a very useful rule of thumb from someone who explains specificity by using poker examples:

Put generic declarations first (body, a) to define the overall styles for the page
Override only those values necessary in the different sections with ID or class selectors (#navigation.a, .article)
Zero in on specific areas with additional ID or class selectors (#navigation ul.subsection a, #footer p a)

Other useful articles on the topic include:

PHP Operators

What are operators? Things you can execute operations with. PHP has different kinds of operators:

Arithmetic operators

For Mathematical operations. Choose of the following:

  • + Addition
  • – Subtraction: Subtracts a value from a variable
  • * Multiplies
  • / Divides
  • % Modulus: Gives the remaining number when using division
  • ++ Increments
  • – – Decrements

Note: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.

– by php.net

Assignment Operators

Assigning Values to Variables.

  • = Variable equals number
  • += Adds value to variables (not replaces variable)
  • -= Decrease value from variable
  • *= Multiplies value to variable
  • /= Divides value from variable
  • .= used in strings to concatenate: $j.=$k is equivalent to $j . $k
  • %= Modulus

Comparison Operators

Often used in if statements when comparing 2 items

  • == is equal to // NOTE: Don’t mix up with assignment operator =
  • != is not equal to
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

Logical Operators

Usually it is used to combine the results of other operators and returns true or false.

  • && and
  • and Low-precedence and
  • || or
  • or Low-precedence or
  • ! not
  • xor Exclusive or

How to Open a PHP File from your Localhost

And another one from these life saving tips and problem-solving where the answer is so simple that people don’t even understand the question and you feel like the dumbest thing ever afterwards.

Problem: You set up your local development environment, you have apache running and set up to read php files, you installed an integrated development environment (IDE), and to make things easier for you your partner even helped you to find the files in your Finder so you don’t have to use bash to often (which most of the times still gives me this cryptic white characters on black screen feeling).

Then you try to open a php file which you know worked before, but suddenly your browser just won’t interpret it anymore. No matter how often you click on it in Finder, it just gives you the option to open it with a text editor.

So what went wrong?

Apparently, your browser can’t read php files directly, it needs to run it through an interpreter who does the work for it and returns just a normal html file which the browser can handle fine (that’s why html files can easily be opened without Apache or another interpreter directly from the computer). “But I did all this!” you may cry out. Which is true, but if you just try to open it from the computer directly your browser isn’t smart enough to ask apache for interpretation. It just treats it as a normal file. For the file to be shown in the browser you actually need to type in the URL in the browser window, and then the browser will go and look for the file on your computer (or wherever it is hosted) and the whole process of asking apache to interpret the file and then having it returned as a readable html can start.

Boom. It’s that easy, if you know it. So just make sure to know the URL of your file and you are good to go. Whoohoo.

Customising tumblr

I decided it is time for a new theme on tumblr. I found a nice one called “Lightweight”. The tags and dates are much nicer integrated, it features a mobile version, and I like the little icons on the left indicating what type of a post it is.

Nevertheless I need to do some customisations. Unfortunately tumblr doesn’t allow you to create a child theme so I’m just messing around with the main theme. To not get confused here are my changes:

Theme Options:

  • Changed link color to #006633
  • Set Background and border color to white

Edit HTML

  • branding h1
    • changed color to #006633
    • changed font to Optima, PT Sans, Arial, Sans-Serif;
  • branding h1 a: added font-weight: bold;
  • h4
    • deleted h4 from heading list (now it reads h1, h2, h3, h5, h6)
    • added h4 below that list: h4 {color:#888888; font-weight:bold; font-family:Optima, PT Sans, Arial, Sans-Serif; font-size:18px; clear:both;}
  • edited .post-content h3: {font: 22px/1.6 Optima, PT Sans, Arial, Sans-Serif; font-weight: bold;
  • edited #about img: added display: none;
  • edited #about p: changed font to: Palatino, PT Serif, Georgia, Serif;
  • edited p, ul, ol, dd, pre: added font-family: Palatino, PT Serif, Georgia, Serif;
  • edited .post-content img: deleted margin, padding: 10px, added float: left;
  • added class .imagecap {float: left; text-align: center; margin: 10px 15px 0px 0px; font-style: italic; margin-bottom: 10px;}
  • edited .post-type-text .post-content ol li: changed “Upper-latin” to “decimal”

Important:
– Always include class=”imagecap” when posting images
– Quotes might need a make-over

Finding the Right Colour

When designing a website choosing the right colours is one of the most important and most difficult parts. It’s good to remember that black, white, and grey are neutral colours which means they go well with everything. Complimentary colours are opposite to one another and create the highest contrast (think IKEA). If you’re just looking for a specific CSS colour code, I find these links helpful:

Matching Colours

For getting an idea about colour harmonies, this article explains it quite straight forward: http://dandyfashioner.blogspot.com.es/2009/09/art-of-color-what-colors-go-well.html (for matching clothes).

This article is a little more in-depth:
http://www.tigercolor.com/color-lab/color-theory/color-theory-intro.htm

And another one:
http://web.mst.edu/~rhall/web_design/color_mixing.html

The colour wheel:

color-wheel

Creating a Colour Palette

Once you understand the basic rules of how to match colours, creating a colour palette for your website becomes a little easier. There are also some great tools on the internet that help creating a nice color palette:

  • The nicest one might be that of Adobe Color CC. Based on your choice of colour and colour rule it spits out 5 different colours from the colour wheel.
  • Color Blender provides you with up to 10 colours based on 2 individually chosen colours.
  • Color Wizard works similar to Adobe Color CC but makes it a bit more fun to play with different colours

This article from Creative Blog provides more tools.

Finding a Colour Based on a Photo or Website

But what would you do when you find a website and you would like to know exactly which colour they are using? I had to translate a blog article and tried to semi-recreate the layout of their blog, so knowing exactly what kind of colours they were using was very important. Luckily, I found two tools that were extremely useful:

  • My mac books in-built Digital Color Meter
  • Color Hex

The Digital Color meter follows your mouse and shows the RGB colour it is hovering over on a pixel basis.

digitalcolormeter

Once you figured out the right RGB, you can go to Color Hex, type in the RGB (RGB followed by the number, so e.g. RGB 102 47 88) and the tool will provide you with in-depth information about the colour, including it’s CSS colour code.

Based on this I created a mock-up that looked similar to their original blog:

blog-copy

My Copy

Their original

Their original

The Code

The CSS code for colours is extremely simple:

  • {color: #XY;} will change the color of the text
  • {background-color: #XY} will change the background colour of the item

Background colours can also be gradient. It’s a bit tricky, but these articles have some pretty nice code examples:

This was the code I used, and it seems to work fine on the latest versions of Firefox, Chrome, and Safari:

  • style=”background:linear-gradient(#23689f,#54a8e5);”
  • style=”background:linear-gradient(#83939c,#ca9891 5%,#8e271b 45%);”

The percentage numbers mark colour stops. I haven’t quite figured out how they work and it is based more on trial and error than anything else.

How to set up your local server

Now that we know what we need in order to set up a server on a computer it’s time to prep your own one. This article will create a MAMP environment – meaning a server based on MacOS, Apache, MySQL, and PHP.

Understanding Bash, iterm, and vim

First thing to know is that the “Finder” won’t help much for most of the things you’re going to do. The Finder and the rest of the GUI makes it easy to find your way around applications and files, but it also hides a lot of the OS and its functions from you. Not so the “Shell” which will be the “Bash” shell if you’re using a Mac (and a lot of times also when you’re using Linux). Oddly enough, this was once created to make conversation between the OS and the user easier, although nowadays it just looks like a black screen with some cryptographic code.

The nice thing about Bash is that it allows you to access stuff that is usually hidden from the user on the GUI. To do so, you need a terminal window, either the pre-installed one on mac, or you can download iterm. The terminal is used to interact with Bash. Finally, for editing stuff on the terminal, you need vim, which is basically a text editing program without a GUI. It’s usually pre-installed on macs.

Apache and PHP

Apache is usually pre-installed on macs, but if it’s not, you need to download it from the net. To find out if it’s installed use the command “httpd -v” – if it’s installed, it should show you the version of Apache on your computer. But what you need to do is making it usable for PHP files. PHP should be preinstalled on Apache and you just need to comment it in. Other programming languages have to be downloaded I guess. For PHP, you simply have to remove the “#” in front of the PHP module in the Apache file. This will program Apache to process PHP files. Where is the Apache config file located? Most likely either in the var directory or the etc directory of your root. Since it’s a config file you want to edit, etc is more likely to have it. So cd /etc/apache2 should bring you to the right folder. Then, open the config file with vim by typing “sudo vim httpd.conf”. it will ask for your password. After entering the password for your computer and hitting enter the file will be open in vim.

  • Finding the file in vim: /php will search for the php module. keep in mind that these programs are case sensitive.
  • Editing: hit “i” which will start the insert mode. Delete the “#” in front of “LoadModule php5_module libexec/apache2/libphp5.so”
  • Quit editing: hit “escape”
  • Save: type “:w” this will “write” (save) the file.
  • Quitting vim: “:q” will go out of vim and into the terminal again.

Installing MySQL

Follow the instructions on coolestguidesontheplanet: http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/

Creating a new file on localhost

Use iTerm (bash) to edit some files:

  • httpd-vhosts.conf: Do that by going to /private/etc/apache2/extra (that’s where the file is located)
  • open vim to edit the file (always use sudo command before that: sudo vim httpd-vhosts.conf will open the file
  • in vim edit the config file similar to an html file:

    DocumentRoot “/usr/docs/dummy-host.example.com”
    ServerName dummy-host.example.com
    ServerAlias http://www.dummy-host.example.com
    ErrorLog “/private/var/log/apache2/dummy-host.example.com-error_log”
    CustomLog “/private/var/log/apache2/dummy-host.example.com-access_log” common

    This will create a new “server” on localhost (which is basically just a folder):

    DocumentRoot is where all your web files are located (it’s a directory, inside the directory put your web files)
    ServerName is the website domain (awesomephototours.com)
    ServerAlias is optional if you like to modify your server name
    ErrorLog is where stuff gets stored when something goes wrong
    CustomLog remembers requests to web pages (like history in web browser)
    DirectoryIndex specifies which file to go to when not specified

    After that you need to tell your computer that the folder is on your computer by editing the hostfile (“hosts”):

    “hosts” is located in the /etc directory.
    Use sudo vim hosts to edit the file
    Create a new IP and tell it what website it is
    Now everytime you type that URL in your browser it will first serve that URL mentioned in the hosts file
    A # in front of the file will deactivate that line, to activate it again delete the #.

    Important! When you make changes to virtual host file you need to restart apache for it to restart the file again
    Before restarting apache you need to run the command “sudo apachectl configtest” to make sure there are no syntax errors in your code. Otherwise the server won’t start. It should spit out the line “Syntax OK” if you read that it means you can restart Apache.

    Keep in mind that if the URL in the hosts file is activated (so not “commented out” with a # in front of it) it means that the browser will ALWAYS show the URL specified in your computer. So if you have a WordPress blog it won’t show the version on your www server but the “dev” version on your computer. To show the “real version” again, you need to place the # in front of the URL in the file.

    Apache and VirtualHost

    In order for Apache to read the virtual host file, you need to allow Apache to process virtual host. Go back to /etc/apache2 and remove the # in front of “Include /private/etc/apache2/extra/httpd-vhosts.conf” (underneath “Virtual hosts”)

    Bash/Shell

    Commands
    cd: change directory
    ls: list directory
    ls -l: long (gives additional information about the directory
    ls -la: gives even more information, can show you hidden files
    cd ~: brings you back to my personal home directory
    pwd: shows you where you are right now
    cd /: brings you to root directory
    cd ..: brings you one directory up
    control + c: breaks whatever you’re doing (interrupt)
    less and more: allows you to look at stuff –> in less: control + u/d makes it go up/down, /xy lets you find stuff
    cp: copy
    mv: move
    control +a: going back to the beginning of the line
    mkdir: makes a directory
    sudo: gives you permission when you don’t have permission by default. Basically, whenever a command doesn’t work because the permission is denied, use that and then type in your password to access the computer
    drwx stands for: directory (so type of content) – read – write (means you can make changes to it) – execute (means you can execute it)

    Important

    When you are in a program (Apache, less, vim..) you can’t “scroll” up – you need to use key combinations such as “control + u/d” for moving up/down.

    relative vs. absolute paths: / means it’s an absolute path, without it cd will just go relative to where you are now

    When you want to copy or move a directory/file, simply type cp/mv followed by the name position where it is right now and after that the position and name where you want to copy or move it.

    important directories
    etc: holds most config file
    var: where you would normally put your webfiles. Also where logfiles are stored.

    What is a local server and why do I want one

    A local server is a server that is running exclusively on your computer. You don’t need to connect to the internet to actually create a website (at least not a website that only you want to see). Any website can be created on a computer. Any server basically is a computer – just one that is optimized to run web applications and is connected to the www. This also means that any computer can be turned into a server – you just need to install the right applications and software.

    Why would I wanna have a local server?

    Local hosts are awesome if you want to create a local web development environment. It allows you to run an application (e.g. a WordPress blog) directly from your computer so you can play around with it as much as you like without anyone knowing about it. You basically have a cheap and secure dev server where you can test all the changes you want to make on your website without changing the actual site. Nice.

    Stuff you need for setting up the server

    Since the computer is a machine and machines are quite powerful but (still) also pretty dumb you first need to install and configure every program and software you need for running a web application. Machines haven’t figured out how to learn on their own yet so the computer can only do what someone else programmed and “taught” it to do. Since a personal computer is usually not used to run web applications a few things are missing and need to be configured in order to create a web development environment.

    An OS

    This would most likely be either Mac, Windows, or Linux. The operating system is where all of the applications and software that you need is installed.

    Apache

    Apache is used to connect the outside world with the stuff that is saved on the server. A lot of people refer to it as actually being the web server, as this is basically what it does. It “serves” web pages to the internet. When someone visits a website in a browser the browser will go to Apache and ask for the website. Apache then processes this request by either grabbing everything it needs by itself (which basically is the case for static pages) or it uses someone else (the programming language) in order to get everything it needs to serve the requested website. But, Apache is a program and therefor it can only do the things someone else has taught it to do. If, for example, no one has taught Apache how to read PHP files it can’t process requests from pages based on PHP. So always make sure that Apache is set up correctly and can read and process all the requests that are necessary to gather together the information needed to serve the browsers request.

    Data Base

    In my (and the most common) case: This would be MySQL. What does the database do? It stores your (dynamic) data. This is a bit difficult to understand. Static pages, those that actually need to be overwritten by using an FTP server every time you change the text or picture or other components of the website, don’t need a database. Most of the time they’re purely based on CSS and HTML and stored on a disk inside the server, as you would store any other file in your computer. Dynamic pages are the ones you can actually change on the fly, for example in WordPress. You just hit the “save” button and the new version magically appears on the screen. The frame (the WordPress theme) stays the same – only the content changes. That content is saved in the database. So if you lose your database, you basically lose all of your content. Bad.

    Programming Language

    The programming language is the bridge between Apache and the database. When a request for a page comes in Apache asks the programming language to get everything it needs in order to serve the request. The programming language looks at the list and goes to the database in order to get everything, puts it together, and serves it back to Apache. One of the most popular programming languages is PHP. This is what WordPress uses to interact with the database.

    In the real world

    My favourite teacher likes to find real world examples to explain heavy and abstract stuff, and he is pretty good in it:

    When a customer (the browser) comes into a restaurant (the OS), he calls the waiter (Apache) to order something from the menu. The waiter (Apache) then goes to the cook (Programming language) which looks at the dish to see what kind of ingredients it needs. The cook (programming language) then goes into the storing room (database) to get all the necessary ingredients, preps them, and gives the end product to the waiter (Apache) who serves it to the customer (browser).

    But this whole process is only needed when the content is constantly changing, or when the content has to be prepared freshly every time someone visits the website. This is what a dynamic website does.

    But if, for example, all the food is precooked, the waiter (Apache) can skip all the cooking (programming language) and prepping (database) stuff and just hands an already prepped sandwich over the counter. This would be the static website.