Skip to main content

How to Make an Element with Absolute Position But Relative to Its Parent in CSS

There are a few ways to position child divs within a parent div using CSS. One way is to use absolute positioning. However, the browser will render the child’s position relative to the document’s body.

If you want to absolutely position an element inside of a container, but you want it to be relative to its parent, you need to set the parent’s position property as relative.

<div class="parent">
    <div class="child">Absolute element</div>
</div>

<style type="text/css">
.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    right: 50%;
}
</style>

Example with more styles:

.parent {
    position: relative;
    height: 500px;
    background: #EEE;
}

.child {
    position: absolute;
    top: 50px;
    right: 0;
    height: 30px;
    width: 139px;
    background: green;
    color: white;
    text-align: center;
    padding-top: 10px;
}

By continuing to use the site, you agree to the use of cookies.