Reputation: 187
I'm trying to center multiple elements around a single element vertically and horizontally.
In the case the blue element is first, it needs to be in the absolute middle of the page and all green elements need to be aligned after it.
In the case the second element is blue, it needs to be in the absolute middle of the page, and it needs to have one element above it, and one element below it.
In the case the third element is blue, it needs to be in the absolute middle of the page, and it needs to have two elements above it and and element below it.
I also want to do the same thing for columns as well.
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="./index.css"/>
</head>
<body>
<div class='row'>
<div class='column'>
<div class='box blue'></div>
<div class='box'></div>
<div class='box'></div>
</div>
</div>
</body>
</html>
CSS:
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.row {
height: 100%;
display: flex;
flex-direction: row;
justify-content: center;
}
.column {
flex-direction: column;
display: flex;
justify-content: center;
}
.box {
height: 50px;
width: 50px;
margin: 5px;
background-color: #2ecc71;
}
.blue {
background-color: #3498db;
}
JSFiddle: https://jsfiddle.net/gessha/x18nfaeo/
Upvotes: 2
Views: 189
Reputation: 778
I don't think you can do it with a CSS only general solution. I mean, in case of you have an undeterminated number of child elements. With javascript you could calculate the position and translate the elements to get the desired result. In the case of three elements, I have modified your fiddle and change the order of the flex items using pseudo selectors (nth-child
) to allow position the blue element on the center, but is a very much tailored solution to your test case.
https://jsfiddle.net/t38gorzx/
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.row {
height: 100%;
display: flex;
flex-direction: row;
justify-content: center;
}
.column {
flex-direction: column;
display: flex;
justify-content: center;
}
.box {
height: 50px;
width: 50px;
margin: 5px;
background-color: #2ecc71;
}
.box:nth-child(1):not(.blue) {
order: 1;
}
.box:nth-child(2):not(.blue) {
order: 2;
}
.box:nth-child(3):not(.blue) {
order: 3;
}
.box.blue:nth-child(1) {
order: 3;
}
.box.blue:nth-child(2) {
order: 2;
}
.box.blue:nth-child(3) {
order: 1;
}
.blue {
background-color: #3498db;
}
<div class='row'>
<div class='column'>
<div class='box blue'>1</div>
<div class='box'>2</div>
<div class='box'>3</div>
</div>
</div>
Upvotes: 1