In child-container 1 I would like the two grandchildren divs to behave indepedently. Aim: Grandchild 1: Left top Grandchild 2: Center spanning entire width.
=Centering grandchild 2 works fine. However, when I add grandchild 1 it behaves according to the container, cutting into the width of grandchild 2 sitting on the same line. How can I move grandchild 1 to the top left?
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.child1 {
background-color: blue;
height: 10rem;
display: flex;
justify-content: center;
align-items: center;
}
.child2 {
background-color: red;
height: 10rem;
}
.child3 {
background-color: green;
height: 10rem;
}
.grandchild1 {
background-color: yellow;
}
.grandchild2 {
background-color: purple;
border: 1px black solid;
flex-grow: 1;
text-align: center;
}
<html>
<body>
<div >
<div >
<div >
<h1>Top-Left Me</h1>
</div>
<div >
<h1>Center Me Entire Width</h1>
</div>
</div>
<div >
<h1>.</h1>
</div>
<div >
<h1>.</h1>
</div>
</div>
</body>
</html>
CodePudding user response:
This will work if you set the position
to absolute
on .grandchild1
and set top
and left
to 0
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.child1 {
background-color: blue;
height: 10rem;
display: flex;
justify-content: center;
align-items: center;
}
.child2 {
background-color: red;
height: 10rem;
}
.child3 {
background-color: green;
height: 10rem;
}
.grandchild1 {
background-color: yellow;
position: absolute;
top: 0;
left: 0;
}
.grandchild2 {
background-color: purple;
border: 1px black solid;
flex-grow: 1;
text-align: center;
}
<html>
<body>
<div >
<div >
<div >
<h1>Top-Left Me</h1>
</div>
<div >
<h1>Center Me Entire Width</h1>
</div>
</div>
<div >
<h1>.</h1>
</div>
<div >
<h1>.</h1>
</div>
</div>
</body>
</html>
CodePudding user response:
.grandchild2
need to be set to:
{
width: 100%; // take full width of a row
position: absolute; // do not affect the .grandchild1
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.child1 {
background-color: blue;
height: 10rem;
display: flex;
align-items: flex-start;
}
.child2 {
background-color: red;
height: 10rem;
}
.child3 {
background-color: green;
height: 10rem;
}
.grandchild1 {
background-color: yellow;
}
.grandchild2 {
align-self: center;
width: 100%;
position: absolute;
background-color: purple;
border: 1px black solid;
text-align: center;
}
<div >
<div >
<div >
<h1>Top-Left Me</h1>
</div>
<div >
<h1>Center Me Entire Width</h1>
</div>
</div>
<div >
<h1>.</h1>
</div>
<div >
<h1>.</h1>
</div>
</div>