Fan fiction is written by fans using the characters or setting of a professional original. The fiction is not limited to writing: there are, for instance, fan fiction movies.
There are several ways one can legally do fan fiction:
- Often, it is created as a thoroughly not-for-profit effort.
- Major franchises, such as Star Trek and Lord of the Rings, establish guidelines for what actions will not violate copyright, and then encourage fan fiction and fan movies. There is actually a series of fan fiction episodes continuing on the original Star Trek, and actors from the original series played in it. There is a movie about the story of Aragorn capturing Gollum, as well.
- Sometimes, fan fiction becomes professional fiction. For example, the Star Trek series, the Star Wars series, and other movies have spawned many novels. The right to use the world and characters was licensed to a publisher, and the novelist (who might or might not already be a professional writer, but is certainly a fan) gets royalties, and the movie studio who owns the original series gets a slice, too.
- There is fan fiction for out-of-copyright materials. I'm not sure, but it seems likely that the Sherlock Holmes stories fit in this category. And adaptations of Shakespeare certainly do.
If you are thinking of writing fan fiction, it can be good to reach out to the copyright holder for guidelines.