Jump to content

How to position an element to the top of the visible screen

Donny Bahama

Recommended Posts

I'm using a script that toggles different popup divs when different links are clicked. The problem is the placement of the popup with regard to the screen height. I always want the popups centered horizontally so each popup has margin-left and margin-right set to auto -- but setting margin-top and margin-bottom to auto doesn't work. Is there some way to position the popups at the top of the visible screen so that even if it's viewed on a relatively small screen (i.e. a smartphone in portrait mode), the popup will still pop up in a place that's vertically appropriate, regardless of how far down the page the user has scrolled?

The fact that position:sticky exists makes me think that there must be some way of doing this but when I try to detect where the top of a sticky background image is, I always get 0px.

Link to comment
Share on other sites

For a popup you can use fixed position and vh units, which refer to percentage of the viewport height.

.popup {
  position: fixed;

  top: 5vh;
  height: 90vh;

  /* Center horizontally */
  left: 50%;
  transform: translateX(-50%);
  width: 900px;
  max-width: 95vw;


Link to comment
Share on other sites

Either one will work, its used to insert a text element to help vetically align the popup content box as it need something to align to, this also uses display: inline-block so it acts as text would with text-align and vertical-align, you can change to top/bottom whatever.

Edited by dsonesuk
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...