Search code examples
htmlcsscontainerscenterinline

4 divs and need to center 2 center divs


I have four divs inside a container like this:

<div class="container">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
</div>

I would like to keep the first and last div aligned to the edges of the screen and only center the two divs in the middle. I tried display inline block and adjusting the margins, but i just can't figure it out. Please try and enlighten me!

Kind Regards


Solution

  • Use this HTML

    <div class="container">
        <div class="block left">1</div>
        <div class="block">2</div>
        <div class="block">3</div>
        <div class="block right">4</div>
    </div>
    

    and then this CSS

    .container {
        display:block;
        text-align:center
    }
    .block {
        display:inline-block;
        border:1px solid #000;
        padding:10px;
        margin:auto
    }
    .left {
        float:left
    }
    .right {
        float:right;
    }
    

    you can also use first-child and last-child, but it's easier to add a class to first and last div

    See fiddle here