I was working on my portfolio and I needed to center a div to the viewport height and width.. by using calc I was able to achieve it but I want to center divs without needing to type the calc over and over again
/*what i tried*/
#piece{
top: calc((150px - attr(height))/2);
left: calc((150px - attr(height))/2);
position: absolute;
}
.piece-1{
height: 150px;
aspect-ratio: 1/1;
background-color: #00FEFC;
}
.piece-2{
height: 100px;
aspect-ratio: 1/1;
background-color: #FF3131;
}
.piece-3{
height: 70px;
aspect-ratio: 1/1;
background-color: blanchedalmond;
}
.piece-4{
height: 40px;
aspect-ratio: 1/1;
background-color: aquamarine;
}
<div class="loading">
<div class="piece-1" id="piece"></div>
<div class="piece-2" id="piece"></div>
<div class="piece-3" id="piece"></div>
<div class="piece-4" id="piece"></div>
</div>
here i have divs with different class name and same id. i want to use use calc() to center all of them by just using the attribute name.. i could type the code in all four divs but I was wondering if I could do it in 2 line of codes
>Solution :
Here is a solution without calculation. You can have the same result with transform: translate() for X and Y and display: flex
Also, I have updated your HTML and CSS because each id should be unique.
/*what i tried*/
.loading{
display: flex;
justify-content: center;
}
.piece{
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
position: absolute;
aspect-ratio: 1/1;
}
#piece-1{
height: 150px;
background-color: #00FEFC;
}
#piece-2{
height: 100px;
background-color: #FF3131;
}
#piece-3{
height: 70px;
background-color: blanchedalmond;
}
#piece-4{
height: 40px;
background-color: aquamarine;
}
<div class="loading">
<div id="piece-1" class="piece"></div>
<div id="piece-2" class="piece"></div>
<div id="piece-3" class="piece"></div>
<div id="piece-4" class="piece"></div>
</div>