Alex Rivera | Logout

How to Position an Element Absolute from Center - CSS

Asked 2010-12-16T17:36:17.827
22

For a client, I need to put together an absolute div to the left of the body containing an advertisement. The only way I have figured out how to do this thus far is to create an absolute div. The issue here is that in the absolute positioned div, there is a black space (which is the end of the body) and I need to have this "gutter space" ad hugging the page.

To account for this, the best method is to position this a set number of pixels away from the center of the page. I thought I could do this by the following code:

position: absolute;
left:50%;
margin-right:500px;

However, this just keeps the div in the center of the page. Is it possible to position an absolute div from the center of a page?

Edit
Report

2 Answers

40

If you know the width of the advertisement then you can do this:

position:absolute;
left:50%;
margin-left:-250px;
width:500px;

notice the negative margin-left which is half of the width of the element to be positioned

answered 2010-12-16T17:41:10.450
0

You don't necessarily need to give it absolute position.. You could exploit the default overflow behaviour of block elements.. For example, you could achieve the desired result by using a code like this:

MARKUP:

<div id="adbox">
    <div class="content">
        <a href="#">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nibh  odio, sollicitudin vel sodales vel, dignissim sed lacus. Praesent sed  erat sed turpis gravida congue. Nulla facilisi. Nunc eros eros, auctor  et auctor in, tempor quis magna. Curabitur in justo libero.</a>
    </div>
</div>
<div id="main-content">
    <p>Curabitur iaculis, dolor eu interdum fermentum, mi mauris vulputate est,  tempus rhoncus leo dolor nec orci. Duis a ante augue. Suspendisse  potenti. Proin luctus ultrices ligula, ac luctus lorem pellentesque non.  Curabitur sit amet eros dui, quis laoreet felis.</p>
</div>

STYLE:

#adbox {
    width: 400px;
    height: 0px;
    position: relative;
    z-index: 0;
    margin: 0 auto;
}
#adbox .content {
    background: #EEE;
}
#main-content {
    width:300px;
    margin: 0 auto;
    position: relative;
    z-index: 1;
    background: #CCC;
}
#main-content p {
    padding: 0 5px;
}

IE warning: in IE <= 6 the height property is interpreted as any other browser does with min-height: you might want to add some specific style to fix this issue.


Or else, you could absolutely position the ad and go this way: http://jsfiddle.net/bssxg/10/

#adbox { width: 400px; position: absolute; z-index: 0; top: 0; left: 50%; margin-left: -200px; }

(the left negative margin being equal to half the width of the ad box)

answered 2010-12-16T20:57:12.553

Your Answer