Search code examples
htmlcsspositionscalecenter

Positioning vertical center


I want to center these 4 images. Horizontally it is working but vertically it won't work. Does anybody knows how to solve this problem? At the moment I've got a black header/footer section with 4 images centered horizontally. Everything is scalable but not the height of the images.

Am doing it right?

HTML:

<section>
    <div class="pic">
        <img src="img.png" alt="Pic" />
    </div>
    <div class="pic">
        <img src="img.png" alt="Pic" />
    </div>
    <div class="pic">
        <img src="img.png" alt="Pic" />
    </div>
    <div class="pic">
        <img src="img.png" alt="Pic" />
    </div>
</section>

CSS:

body {
    margin:0;
    padding:0;
    max-width: 100%;
    max-height:100%;
}
section {
    position:absolute;
    top:5%;
    bottom:5%;
    left:0;
    width:100%;
    height:90%;
}
section img {
    width:12.5%;
    float:left;
    margin-left:10%;
}

Solution

  • I think its easier to wrap the images in a container and then center the container in the container's parent, in this case you could use an Article tag to wrap the images an then center that article in the section like this

    HTML

    <section>
        <article>
            <div class="pic">
                <img src="img.png" alt="Pic" />
            </div>
            <div class="pic">
                <img src="img.png" alt="Pic" />
            </div>
            <div class="pic">
                <img src="img.png" alt="Pic" />
            </div>
            <div class="pic">
                <img src="img.png" alt="Pic" />
            </div>
        </article>
    </section>
    

    CSS

    html, body {
        height: 100%;
        width: 100%;
    }
    
    section {
        top: 5%;
        left: 0%;
        width: 100%;
        height: 90%;
    
        /* strech */
        overflow: hidden;
    }
    
    article {
        width:80%;
        height:40%; /* change this to set height */
    
        /* CSS absolute center begin */
        border: 2px solid #0000ff;
        margin: auto;
        position: absolute;
        display: inline-block;
    
        top: 0;
        bottom: 0;
        left:0;
        right:0;
        /* CSS absolute center end*/
    }
    
    .pic {
        position: relative;
        float: left;
        width: 12.5%;
        height: 100%;
        margin-left: 10%;
    }
    
    .pic img{
        position: relative;
        width:100%;
        height:100%;
    }
    

    Hope it help you