lhan
lhan

Reputation: 4635

center element within another, while parent specifies position: absolute?

I'm working with this JS Fiddle: http://jsfiddle.net/BY3tz/1/

Notice when you remove the position, left, and top properties from the dotParent CSS class, the black dot is centered within the box.

I'm looking for a way to keep the black dot centered (vertically and horizontally) while leaving the 3 properties mentioned above in place so that I can change the left and top properties to position the box anywhere, and the black dot will remain centered.

Is this possible? Can anyone see what I'm doing wrong with my dot class?

Upvotes: 1

Views: 3494

Answers (3)

Change the position attribute in the dotParent div to "Relative". Since its the parent Div, it needs to be positioned as Relative in order for its children to take it as a reference point.

.dotParent {
    position: relative;
    top: 150px;
    left: 50px;
    height: 68px;
    width: 68px;
    border: 1px solid Black;
}

http://jsfiddle.net/BY3tz/6/

Upvotes: 1

Christopher Marshall
Christopher Marshall

Reputation: 10736

Added dot wrapper so .dot is relative to new wrapper,

<div class="dotParent">
    <div class="dot-wrapper">
        <div class="dot"></div>
    </div><!-- end dot-wrapper -->
</div>

New Styles.

.dot-wrapper {
    position:relative;
    width:100%;
    height:100%;
}

Added to .dot class

.dot {
    position:absolute;
    top:45%;
    left:45%;
}

http://jsfiddle.net/BY3tz/5/

Upvotes: 2

Kaloyan
Kaloyan

Reputation: 7352

Some tweaks to the .dot class:

.dot {
    position: absolute;
    width: 10px;
    height: 10px;
    border-radius: 50px;
    margin-left: -5px; // Half of the width * (-1)
    margin-top: -5px; // Half of the height * (-1)
    top: 50%;
    left: 50%;
    background: #000;
    -webkit-border-radius: 50px;
    -webkit-background-clip: padding-box;
    background-clip: padding-box;
}

http://jsfiddle.net/BY3tz/2/

Upvotes: 5

Related Questions