Position absolute centering div

Hi,

I am working on something where I need to display an element on the top of a page centered. I have put some HTML together shown below:


<html>
    <head>
        <style type="text/css">
            body {
                background: #c0c0c0;
            }
            .test {
                padding: 5px 27px 3px 5px;
                background: #fff;
				position: absolute;
				top: 0;
				left: 50%;
				margin-left: -75px;
            }

            .arrow {
                height: 17px;
                width: 17px;
                background: #f00;
                position: absolute;
                top: 6px;
                right: 4px;
            }

        </style>
    </head>
    <body>
        <div class="test">
            THIS IS SOME TEST DATA
            <div class="arrow">
                &nbsp;
            </div>
        </div>
    </body>
</html>

What I am trying to do is when the text expands the div expands from left and right outwards. At the moment if i enter more than just ‘THIS IS SOME TEST DATA’ it expends from the right. Can I achieve this?

If you use the above markup, you will see a red box. This will be an arrow but I have used this just as an example. That red box will always need to remain on the right of the text…

Thanks :slight_smile:

Can I achieve this?

Hi,
Sure, that can be done.

What you’ll need to do is set the AP element to 100% width and just use it to keep it’s children removed from the normal page flow.

Then set an inline-block child i it and center it with text-align:center on the AP parent. An inline-block is a shrink wrapping element too so it will expand to the with of the content.

As far as the arrow, I would just set some right padding on the inline-block and make it a background image rather than the :after element I used below.

If you need to support IE 6/7 you can use the tripswitch for them since they do not have native support for inline-block.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test Page</title>

<style type="text/css">
body {
    background: #c0c0c0;
}
.test {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    text-align: center;/*center the inline-block child*/
}
.test p {
    display: inline-block;/*shrink wrap to width of content*/
    margin: 0;
    padding: 5px;
    background: #fff;
}
.test p:after {
    float: right;
    content: "";
    width: 17px;
    height: 17px;
    margin-left: 5px;
    background: #f00;
}

</style>
</head>
<body>
    <div class="test">
        <p>This Is Longer Line of Some Test Data</p>
    </div>
    <p>This is some content in the normal page flow</p>
</body>
</html>

Thanks, that has got me going. I will try and get this working in IE as well :slight_smile: