Search code examples
cssresponsive-designliquid-layout

How does the padding work in responsive CSS square?


I am now learning how to develop responsive liquid CSS designs and came across technique, where block display elements (eg. div) have % dimensions. In order to display them, the following CSS code is used:

.class:before {
    content: "";
    display: block;
    padding-top: 100%;
}

My confusion comes from padding property. As far as I know, in the CSS box model (CSS2), padding affects the inner part of the block element, not outer. But in the technique used, without it, element is not visible. Could somebody explain to me in terms of box model, what padding property does here?

In case my explanation is confusing, I am attaching two links with working examples:

http://www.mademyday.de/css-height-equals-width-with-pure-css.html

http://jsfiddle.net/josedvq/38Tnx/

Alexander.


Solution

  • CSS pseudo element ::before (:before) or ::after (:after) + content property, creates a child element inside the container.

    And a percentage padding value is relative to the width of the container - W3C spec, padding-top:100% + display:block creates a square.

    .square {
        width: 10%;
        background: blue;
    }
    .square:before {
        content: "";
        display: block;
        padding-top: 100%;
    }
    <div class="square"></div>