Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to top align a div inside another div

Tags:

css

enter image description here

Hi

I want to place the div2 top align with the div1's border

So far I have tried this for div 2 but it did not work out well

element.style {
    float: right;
    position: relative;
    vertical-align: top;
}

this did not align the div at top position , what could be the fix to make it top aligned?

like image 393
Gayan Kalanamith Avatar asked Dec 04 '25 14:12

Gayan Kalanamith


1 Answers

I would achieve this using position: absolute; on the child like said before, but instead of adding an additional div to the DOM to simulate use the space , I would use a pseudo-element (more precisely, the ::before pseudo-element).

This is the structure I used for it:

<div class="parent">
    <div class="child">

    </div>
    <h1>Start</h1>
</div>

The div with class parent needs to be position: relative;, and the child needs to be absolute to it and set to be top: 0; like the following lines explain:

.child {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100px;
    background-color: #000;
}

You will though need to set this element a fixed height and width, otherwise it will not work.

The problem of this approach is that you will have a div that will be over the first 100px of your .parent div.

To solve this we need to create a pseudo-element on the .parent div that will simulate that space and make everything work better:

.parent:before {
    display: block;
    content: ' ';
    width: 100%;
    height: 100px;
}

Here's a working fiddle with a sample code, hope this helps you!

http://jsfiddle.net/m54rxwjv/2/

PS: This will only work if you know that the height will always be 100px.

like image 139
Matias Avatar answered Dec 10 '25 14:12

Matias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!