Search code examples
htmlcsscentering

Centre multiple elements within div using css


I'm new to html and css and I'm trying to create a website, part of the code is here:

HTML:

<div class="row">
    <div class="circle"></div>
</div>
<div class="row">
    <div class="circle"></div>
    <div class="circle"></div>
</div>
<div class="row">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
</div>
<div class="row">
    <div class="circle"></div>
    <div class="circle"></div>
</div>
<div class="row">
    <div class="circle"></div>
</div>

CSS:

.circle
{
border-style: solid;
border-color: red;
width: 70px;
border-radius: 40px;
float:left;
margin: 2px;
}

.row
{
border-style: solid;
border-color: black;
height: 100px;
width: 700px;
margin: 10px;
}

http://jsfiddle.net/ubd9W/

I'm trying to centre red circles (horizontally and vertically) within the black boxes but I can't seem to manage it. I've tried using 'text-align' and setting the left and right margin to auto but that doesn't work. I also can't use 'absolute' positioning because I have a fixed menu bar at the top of the page and that gets ruined if you scroll.

Any help will be greatly appreciated. Thanks


Solution

  • very simple to understand with the same code you provide you just need to give the parent element a text-align:center; and a position:relative;

        .row{
            border:4px solid black;
            height: 100px;
            width: 700px;
            margin: 10px;
            text-align:center;
            position:relative;
        }
    

    then set the children margin:10px auto; and display:inline-block;

        .circle{
            border:4px solid red;
            height: 70px;
            width: 70px;
            border-radius: 40px;
           position:relative;
            margin:10px auto;
           display:inline-block;
        }
    

    or if you want more margin between them change margin:10px auto; to margin: 10px 40px;

    demo: http://jsfiddle.net/ubd9W/14/