Code Corner: Nested Squares


Problem

Draw three nested squares in html and css.

My Solution

Simple, you need three divs nested inside each other with a unique way of referencing them, the rest is done in CSS.

<div id="first" class="wrapper">
    <div id="second">
        <div id="third"/>
    </div>
</div>Code language: HTML, XML (xml)

I set the body to gray because reasons, there is really no need to do this. The first part is that all divs on the page get a 60% width and height and their positions are set to absolute. We give them a 20% margin top and left and a solid border.

The top div is our wrapper and needs slightly different values, thus we override our height, width, position and margins.

div {
    height: 60%;
    width: 60%;
    margin: 20% auto auto 20%;
    position: absolute;
    border-style: solid;
}

.wrapper {
    height: 500px;
    width: 500px;
    position: relative;
    margin: 50px auto;
}Code language: CSS (css)

The final piece of the puzzle is the colors for our divs.

#first {background-color: darkred;}
#second {background-color: white}
#third {background-color: darkblue;}Code language: CSS (css)

This results in something like this:

Michael | MMusangeya

You can fiddle with this here. And done.


Leave a Reply

Your email address will not be published. Required fields are marked *