ScanSkill
CSS Examples

How to Position a Div at the Top of its Container using CSS?

In this example, we will learn how to position a div at the top of its container using CSS. We will be using the position and top property along with other CSS properties.

Prerequisites

HTML

<div class="container">
        <span class="my_div">Hello ScanSkill</span>
    </div>

CSS

.container {
            position: relative;
            height: 300px;
            background-color: red;
            color: white;
            text-align: center;
        }

        .my_div {
            position: absolute;
            top: 0px;
            background-color: black;
            padding: 10px;
        }

Output

How to Position a Div at the Top of its Container using CSS

Here, we positioned the container relative to the browser’s viewport using position: relative and positioned the my_div relative to the container using position: absolute, and made it display at a distance of 0px from the top using top: 0px. We aligned the text at the center of the container using text-align: center. We specified the background color, height, and padding using background-colorheight, and padding property.

Conclusion

In this example, we learned how to position a div at the top of its container using CSS. We used the position and top property along with other CSS properties.