Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using calc() to center divs

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading