How does flexible CSS square shim work?
Now I am learning how to design flexible fluid CSS designs and came across a technique where block display elements (like a div) have% sizes. The following CSS code is used to display them:
.class:before {
content: "";
display: block;
padding-top: 100%;
}
My confusion comes from the padding property. As far as I know, in the CSS box model (CSS2), padding affects the inside of the box element, not the outside. But in the technique used without it, the element is not visible. Can anyone explain to me in terms of the box model what the padding property is doing here?
If 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.
source to share
CSS pseudo-element, ::before (:before)
or ::after (:after)
+ content
property, creates a child element inside a container.
And the percentage padding
relative to the width
container is 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>
source to share
The main answer is that if you have an empty element in HTML, the width and height of the element displayed on the page will be 0, making the element invisible. It makes sense: if there is nothing in it, and the size is 0, who wants to see it!
What you do with padding is 100% of the parent field's value to pad. Because padding affects the inside of the box (and leaves it on the outside), the overall width and height of the box changes. This makes the window draw on the screen and creates the blue square you saw in the jsFiddle.
The reason your box is not showing up when you delete it is because of an attribute overflow: hidden
. When you say this, you are cutting out any additional content out of the box if the content inside was supposed to overflow the size of the box. If you delete overflow: hidden
and padding 100%
, you get a little white text.
EDIT: A couple of other things that are happening: Youre also using position: absolute
that removes the field element from the regular flow of the page. This and the next four tags top, left, bottom, right
make the field a predefined location. Removing position: absolute
brings the div back as a blue square around white text
This is the opinion: CSS is a nightmare. This is not an opinion: a great way to learn CSS would be to add or subtract lines of CSS once to see what they do individually. W3 Schools also has a huge list of every attribute in CSS and HTML, which means you can usually find out how everything in those languages should work by searching for "W3 mythingyhere"
source to share