I'm trying to lift an inner div outside of its parent with the negative margin.
Supposing the following structure:
* {
margin: 0;
padding: 0;
}
.grand-parent {
height: 300px;
width: 100%;
background: pink;
}
.parent {
height: 150px;
}
.grey {
background-color: grey;
}
.child {
height: 50px;
}
.required {
width: 70%;
background-color: yellow;
}
<div class="grand-parent">
<div class="parent">
<p>Neighboring parent </p>
</div>
<div class="parent grey">
<div class="child required">
<h1>
Required Heading
</h1>
</div>
<div class="child last">
<h2>
Other Heading
</h2>
</div>
</div>
</div>
I would like to lift the "Required heading" as well as all the consequent tags up, outside the parent element by applying the negative margin, so that the parent's background/margins are not affected. I am able to achieve this behavior when there is another child element coming before the "Required heading", like that:
* {
margin: 0;
padding: 0;
}
.grand-parent {
height: 300px;
width: 100%;
background: pink;
}
.parent {
height: 150px;
}
.grey {
background-color: grey;
}
.child {
height: 50px;
}
.first {
background-color: lightgrey;
}
.required {
width: 70%;
background-color: yellow;
margin-top: -120px;
}
<div class="grand-parent">
<div class="parent">
<p>Neighboring parent </p>
</div>
<div class="parent grey">
<div class="child first">With another child</div>
<div class="child required">
<h1>
Required Heading
</h1>
</div>
<div class="child last">
<h2>
Other Heading
</h2>
</div>
</div>
</div>
But without the "first child" the "Required header" actually lifts the parent fully, like so:
* {
margin: 0;
padding: 0;
}
.grand-parent {
height: 300px;
width: 100%;
background: pink;
}
.parent {
height: 150px;
}
.grey {
background-color: grey;
}
.child {
height: 50px;
}
.first {
background-color: lightgrey;
}
.required {
width: 70%;
background-color: yellow;
margin-top: -120px;
}
<div class="grand-parent">
<div class="parent">
<p>Neighboring parent </p>
</div>
<div class="parent grey">
<!-- <div class="child first">With another child</div> -->
<div class="child required">
<h1>
Required Heading
</h1>
</div>
<div class="child last">
<h2>
Other Heading
</h2>
</div>
</div>
</div>
Can this be achieved without introducing another element?