Search code examples
cssalignment

Vertically aligning only 2 items on a full-screen page


I have more than 2 image items placed in various positions against a full screen background image (container). I only need the two image items in the center to align horizontally down the middle of the page/screen. This also needs to be responsive ie. when the browser window is contracted horizontally I want the two items to move towards the middle in tandem with each other. With the code I am trying, one of the two items is not lining up with the other, and is in fact moving a little left of center when the browser screen is contracted to mimic portrait mode. What is the issue? I am positioning absolutely and using margin: auto on both. Here is the code. Would appreciate any light.

PS, for some reason the arrow is moving up and down in the jfiddle, while retaining its horizontal alignment; this is not happening in my case; in my case the arrow is only retaining its vertical position (as i want it), but moving off centre when i contract the browser width (which is not what i want; i need it to keep it horizontal position at the center as well).


Solution

  • If you want the two divs horizontally and vertically (i.e. the dead center of the screen!) you can use the following CSS...

    #div1,
    #div2 {
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
      margin: auto;
      }
    

    If you want the images to respond to the screens width then adding a maximum width on the images would fix that.

    img {max-width: 100%;}