I have centered a yellow div horizontally and vertically like this:
<div style="position:absolute;width:830px;height:590px;background:yellow;left:50%;top:50%;transform:translate(-50%, -50%);"></div>
I would like to have 4 div around the centered div, so one div on the left side, one div on the right side, one div above and one div below, each in different colors, each should touch only one border of the view-port, and each should touch one border of the centered div.
CodePudding user response:
IMHO the easiest way would be to use CSS-Grid
. Then you can sepcify the placement either definet through the grid-column
and grid-row
placement or by using grid-area
.
To let the elements (divs) touch one border of the viewport, you need to define the height of the grid to 100vh
. Also you need to remove the default body margin
.container {
display: grid;
min-height: 100vh;
grid-template-columns: repeat(3, 1fr);
grid-template-areas:
". top ."
"left center right"
". bottom .";
}
.center {
grid-area: center;
}
.top {
grid-area: top;
}
.right {
grid-area: right;
}
.bottom {
grid-area: bottom;
}
.left {
grid-area: left;
}
/* for demo purpose only */
body {
margin: 0;
}
.container > div {
box-sizing: border-box;
border: 2px dashed black;
min-height: 50px;
display: flex;
justify-content: center;
align-items: center;
}
<div >
<div >Center</div>
<div >Top</div>
<div >Right</div>
<div >Bottom</div>
<div >Left</div>
</div>
CodePudding user response:
I think that other answer is better, but here will an alternative:
.container {
width: 100%;
height: 100vh;
background: purple;
gap: 20px;
padding: 20px;
display: flex;
flex-direction: column;
}
.upper-row,
.middle-row,
.bottom-row {
flex: 1;
}
.upper-row .inner-row {
margin: 0 auto;
background: rgba(255, 255, 255, 0.3);
width: calc(100% / 3);
height: 100%;
}
.middle-row {
display: flex;
gap: 20px;
}
.middle-row .inner-row {
width: calc(100% / 3);
height: 100%;
background: rgba(255, 255, 255, 0.3);
}
.middle-row .inner-row:nth-child(2) {
background: red;
}
.bottom-row .inner-row {
margin: 0 auto;
background: rgba(255, 255, 255, 0.3);
width: calc(100% / 3);
height: 100%;
}
<div >
<div >
<div ></div>
</div>
<div >
<div ></div>
<div ></div>
<div ></div>
</div>
<div >
<div ></div>
</div>
</div>
https://jsfiddle.net/kdsv99/140w56th/16/
CodePudding user response:
If you are doing it to learn, first stop use style on html, but include a css file and second for that matter you should look into flexbox property or grid. You can use display flex create a container with display:flex; that contain 3 elements div1 your div and div2, then inside div 1 and 2 you create other 2 divs and give them display:flex; flex-direction: row; a 25% width ; height auto; your div should have a width of 50%