Search code examples
csspositionmargin

how can I position an element on top of a div witouth using negative margins?


how can I position an element on top of a div without using negative margins or padding? check the image to see what I'm trying to achieve:

enter image description here

grey area is the div #content and blue is h1. I need the h1 to be inside of the #content. I assume I could achieve this if I place h1 before #content div and use z-index but thats not the only way, is it?

<div id="content">
<h1>text here</h1>
</div>

Solution

  • You can use positioning.

    #content h1 {position: relative; top: -15px;}
    

    Or to put it in a better way, give positioning for both.

    #content {position: relative;}
    #content h1 {position: absolute; top: -15px;}
    

    For the query about negative top values:

    Negative values are allowed and would result in the element being moved in the opposite direction to those already stated above.

    References: