Spacecraft like the International Space Station have pressurized cabins and are filled with the same kind of air we breathe on Earth, so the atmosphere on board is made to feel as close to sea level as possible. But microgravity causes astronauts to experience the effects of weightlessness, and setting up a mattress on the floor can't be part of the plan because not only would the astronaut float away after dozing off, the mattress itself would also drift off, creating the potential for midair collisions.
Because of this effect, astronauts could, theoretically, sleep almost anywhere in a spacecraft. Astronauts sleeping during space shuttle missions normally strap themselves into seats or attach sleeping bags to the walls; they'll avoid the cockpit since light from the sun can cause the area to heat up significantly and make slumber uncomfortable. Most of the crew on the ISS choose to sleep in their own cabin or in an ISS module -- American crew members' sleeping quarters are well-ventilated (to prevent breathing in the carbon dioxide you just breathed out), soundproof private cabin-for-one setups where an astronaut can not only catch some Z's but also catch up on e-mail. The catch is that they need to tether themselves to something to avoid floating away in the air currents. Most astronauts choose to sleep as closely to how they would on Earth, in sleeping bags tethered to the floor, the walls, or the ceiling. In the microgravity environment there is no such thing as "up," which means it's just as easy to sleep vertically as you would horizontally back home. It's also important to secure your arms (and legs) to avoid them hovering as you sleep.
Adjusting to sleep in space takes a long time for astronauts. Our bodies and brains are used to certain circadian rhythms -- the 24-hour cycle of waking and sleeping -- and disturbing them can cause sleep difficulties.