There are three main categories of words in Spanish, according to what syllable the stress falls on: agudas, llanas o graves, and esdrújulas. Let's see what these terms mean.
Words are divided in syllables. In order to know which syllable gets a tilde, or written accent mark, you need to count the syllables. The counting goes from the last syllable towards the beginning of the word:
One-syllable words: One-syllable words never have a tilde, except in the ambiguity-breaking cases discussed at the end of this answer.
Agudas: These are the words that have the stress on the last syllable. They get the tilde if they end in -s, -n, or vowel.
café, posición, estás, etc.
- Llanas o graves: The words falling into this category have the stress on the penultimate (second to last) syllable. They get the tilde when they don't end with -s and -n or vowel (the opposite situation from the first category I listed).
cónsul, López, carácter, etc.
- Esdrújulas: These words have the stress falling on the third to last and fourth to last syllable. These words are always written with a tilde.
práctica, próximo, jóvenes, diciéndoselo, etc.
Other rules:
- You put a tilde also on words that have hiatus formed by strong vowels (a, e, o) and weak vowels (i, u), such as:
período, Raúl, actúan, filosofía, etc.
Note that the case of the fourth-to-last syllable can also be called by a specific term, "sobreesdrújula." Example: Less common are the words with the stress falling on the fourth-to-last syllable, such as diciéndoselo.
Adverbs ending with -mente get the accent when they come from an adjective that has it: rápido → rápidamente, cordial → cordialmente. (Source)
Last, but not least, you use it on words that have ambiguity or that require the tilde in special situations:
- tú (subject pronoun) – tu (possessive pronoun)
- él (pronoun) – el (article)
- dé (present subjunctive of dar) – de (preposition)
- mí (prepositional/stressed pronoun) – mi (possessive)
- sí ("yes") – si ("if")
- más ("more" or "plus") – mas ("but")
- sé (present tense of "saber") – se (reflexive/reciprocal/indirect object pronoun)
- té ("tea") – te (unstressed pronoun)
- interrogative pronouns: cuándo, qué, cómo, dónde, cuál, quién – non-interrogative corresponding conjunctions: cuando, que, como, donde, cual, quien
demostrative pronouns éste, ése, aquél – demostrative determinants este, ese, aquel (deprecated rule)
sólo – solo (deprecated rule)