Search code examples
cssalignmentcenterfadeinfadeout

Images on top of each other while centered vert. and hor


I have looked up some tips about how to center a div in the middle of the page. I used this method:

width: 750px;
height: 400px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -200px;
margin-left: -375px;

So, now that the div is in the middle of the page, I need some images inside of it to line up directly on top of one another. If I do this, I can fade them out using jQuery, revealing the new image.

Now, I tried many different techniques to line them up, but none work when they are centered like this.

HTML:

<div class="choose" align="center">
    <h2 id="question">Rock, paper, or scissors?</h2>

    <img src="Images/Rock.png" id="rock">
    <img src="Images/Result/Red Rock.png" id="Selected" style="opacity:1">
    <img src="Images/Paper.png" id="paper">
    <img src="Images/Result/Red Paper.png" id="Selected" style="opacity:1">
    <img src="Images/Scissors.png" id="scissors">
    <img src="Images/Result/Red Scissors.png" id="Selected" style="opacity:1">
</div>

CSS:

.choose {
    width: 750px;
    height: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -200px;
    margin-left: -375px;
}

.choose img {
    margin-left: 5px;
    margin-right: 5px;
    width: 150px;
}

How do I do it?

This is a rock paper scissors game if you hadn't noticed. Here's what I've made so far.


Solution

  • You can position the images with absolute in the same coordinates so they stack on top of each other.

    When your element has a specific width, left:0; right:0; margin:auto; is a cool way to horizontally center it in its relative parent. Same method works for vertical centering.

    .choose img {
        width:150px;
        height:150px;
        position:absolute;
        left:0;
        right:0;
        top:0;
        bottom:0;
        margin:auto;
    }
    

    You can also use this method to offset elements from the center.

    .choose img.rock {
        left:-300px;
    }
    
    .choose img.sci {
        left:300px;
    }
    

    Rock will be 300 to the left and scissors 300 to the right.