user2520969
user2520969

Reputation: 1389

Centering content of div in a container

In my website, i have a series of divs like this:

.box{
   float:left;
   width:143px;
   height:183px;
   overflow:hidden;
}

These divs are inside a simple container like this:

.container{
   margin:70px 190px 0 190px;
   overflow:hidden;
}

I would realize a responsive layout but the divs are not horizontal centered in the container. I tried to add "margin-left:auto;" and "margin-right:auto" but nothing. I have a layout as this:

enter image description here

Instead, i would a layout as this:

enter image description here

Can someone help me?

Upvotes: 0

Views: 56

Answers (4)

Dmitriy
Dmitriy

Reputation: 4503

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.container{  
    overflow: hidden;
    max-width: 500px;
    margin: 0 auto;
}
.box{
    float:left;
    width: 31%;
    height: 183px;  
    background: #f00;
    margin: 1%;
}
<div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>

Upvotes: 0

jad-panda
jad-panda

Reputation: 2547

Solution using FlexBox.

FlexBox Guide

FlexBox Browsers Compatibility

.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
  
    margin:7px 19px 0 19px;
    background-color: red;
}

.box {
    width:143px;
    height:183px;
    margin: 10px;
    background-color: black;
}
<div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>

Upvotes: 2

Lal
Lal

Reputation: 14810

See this fiddle

You can achieve this using display:inline-block;, So kindly remove the float:left used in your CSS.

I have made an example like below,

HTML

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

CSS

.div1{
    margin:10px;
    width:25%;
    height:100px;
    display:inline-block;
    background-color:red;
}

Upvotes: 1

Sumit
Sumit

Reputation: 1639

You can not achieve this using float. You can use display: inline-block.

.box{
    width:143px;
    height:183px;
    overflow:hidden;
    display: inline-block;
}
.container{
    margin:70px 190px 0 190px;
    overflow:hidden;
    text-align: center;
}

Upvotes: 0

Related Questions