Justin808
Justin808

Reputation: 21512

I'm trying to center divs inside of another div

Here is the sample I'm working with. I would like to not use any javascript if possible, and if absolutely required with no other solutions possible I would use jQuery.

The 3 inner divs I'm trying to center are an example. In the end result, these are generated by script so I wont know the width or height to use a negative px size for the margin's in the .circle class.

I'd be willing to change the structure of the div's but I'm looking for something clean and simple, though I would rather change the structure than use javascript.

FF4, Safari(iOS)/Chrome, IE9 are my end targets.

edit:

This is the end result I would like, but its using jquery.

Dan's answer would work as well. It puts the onus on the generating script to calculate the negative margins. This would be acceptable in the end I think but I was hoping that all I would have to provide would be the desired size and not any positioning related information from the generating script.

@thirtydot - Right now, none. I'm coding by hand. in the end this would be generated by either PHP or c# depending on my server platform.

Upvotes: 4

Views: 1048

Answers (3)

Marcel
Marcel

Reputation: 28087

Well if it comes down to it, here's some jQuery action to get the job done.

$(".circle").each(function(){
    $(this).css({top: -$(this).height()/2, left: -$(this).height()/2 });
});

Demo: jsfiddle.net/Marcel/7ucme

Upvotes: 0

Dan Marshall
Dan Marshall

Reputation: 644

Generate negative margins in the same place as the sizes:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <style type="text/css">
    .container
    {
        position: relative;
        width: 500px;
        height: 500px;
        border: 1px solid yellow;
    }
    .circle
    {
        position: absolute;
        -moz-border-radius: 100%;
        border-radius: 100%;
        top: 50%;
        left: 50%;
     }
    .white
    {
        border: 1px solid White;
    }
    body
    {
        background-color: black;
    }
    </style>
</head>
<body>
    <div class="container">
        <div class="circle white" style="width: 100px; height: 100px; margin-top:-50px; margin-left: -50px"></div>
        <div class="circle white" style="width: 200px; height: 200px; margin-top:-100px; margin-left: -100px"></div>
        <div class="circle white" style="width: 400px; height: 400px; margin-top:-200px; margin-left: -200px"></div>
    </div>
</body>
</html>

Upvotes: 4

Kon
Kon

Reputation: 27431

Center with margin: 0 auto.

You don't need to know the width's ahead of time, as long as they are set explicitly.

Upvotes: 0

Related Questions