Quick post on just some fun with CSS. I talk too much about WordPress, not that is a bad thing… just thought it would be good to do something different.
Pretty simple really. The only complicated part of this is the use of the :after pseudo element. We’ll get to that in a minute.
First we’ll look at the HTML. A simple empty div with two classes.
The most important class here is the box class. This is the class we’ll use to style the div into our hollowed box. The second class, center-center does nothing but center the element vertically and horizontally.
Next we’ll work on creating a solid square. We can do this easily by creating a 200x200 pixel square, but really it can be what ever dimension you want.
We should now have a solid square. Now the magic begins!. While there are many pseudo classes at our disposal, this is considered a content related pseudo class. Meaning, its specifically here for us to add content after the element without the need of more HTML markup. The code below will add a white square in the middle of our box.
First thing to take note here, I’m using SCSS. If you don’t understand SCSS/Sass/LESS, no worries, this is pretty simple, the &:after block in SCSS is same as .box:after. The ampersand basically is a reference to the parent selector it is assigned to. For a more in-depth talk about pseudo classes, check out Chris Coyier’s post about it.
Now that we are past that, we’ll first load in some empty content and absolutely position our new square. We’ll need to do this so we can center our new square. That’s where our top and left positioning come in. We’ll set our new box in half the height and width of our large box.
Of course everything we’ve done so far returns nothing. We’ll want to set the width and height to half of that of our large box. So simply put, if the large box is 200x200, we’ll want a 100x100 box and color it white (or what ever color you need to match the simulation of a hole in the box.
The last little thing here is we’ll set a z-index of 2 to ensure the :after element is on top of the large box. And voilà! We have a hollowed out box created with CSS! Woot!
Now get creative with this as this is just only the beginning :)