CSS3 calc() function
I recently happened upon the CSS3 calc() function and knew I needed to give it a try. The first thing I imagined was setting a position:fixed; element dynamically to align with a centered body or content section. You see a lot of social links placed like this to allow a reader to share anytime throughout the article. Usually this is done using javascript but this always seemed excessive to me and a glaring limit of CSS. However, with the calc function, it can be set elegantly in a single, readable line.
#fixed-sidebar { left:calc(50% - 380px - 100px); }
The #fixed-sidebar element is 100px wide and next to #content which is 760px wide (760/2 = 380). We could make it even more dynamic by giving #content a percentage width and it would still align perfectly! Also, here is the rest of the specific css code
#fixed-sidebar { width: 100px; height: 400px; background-color: rgb(150,150,150); position:fixed; top:100px; left:calc(50% - 380px - 100px); } #fixed-sidebar:after { border-left:rgb(150,150,150) 10px solid; border-bottom:transparent 10px solid; border-top:transparent 10px solid; width:0; height:0; position:absolute; content:''; right:-10px; top:20px; }
Now it isn’t perfect yet because IE8 and earlier doesn’t support it and it doesn’t have any backwards compatibility with mobile browsers. All up-to-date browsers have added it but only the most recent versions of android and safari mobile. You could combat this by setting a static amount as a default in this format:
left:calc(expression), default;
Or you can just use a media query to give mobile sized browsers a different layout, which you might already do. In terms of uses, the possibilities are endless; but this adds another dimension when re-visiting a layout for a tune-up. For example, having multiple nested divs all with calc functions could become cumbersome in identifying the original layout specifications. Additionally, I think it will not be truly great until we can nest an attr() or toggle() function inside of the calc() function to allow for things like font sizing based on element height. Not mindblowing since there are plenty of plugins for this, but there will be many js replacements with this functionality.
This also means that CSS is becoming more technical in nature when it begins to have computational functionality and may start drifting beyond some casual programmers. Well, you could say float property did that a long time ago so… Ultimately, I think this is a step in the right direction that enables front-end designers to complete a layout/vision with less scripting. This will also continue the separation for niche programmers who understand the intricacies of CSS3, HTML5 or future versions of each.