CSS3

Combined position offsets with CSS

A simple CSS technique for positioning an HTML element with both a proportional offset and a unit offset.

How often have you wanted to position an element at 25% from the left + 10 pixels? Padding is no good as it’s on the interior but if the element is relatively positioned you could add a left margin. However if the element is positioned absolutely or fixed, you’re out of luck there. To generally handle this kind of layout one could nest a container element and give that the unit offset with a margin or positioning. One could even resort to a JavaScript solution, offsetting the element on page load.

The box model of an element absolutely positioned at 25% from the left + 10 pixels.

The box model of an element absolutely positioned at 25% from the left + 10 pixels.

Well no more cluttering your template with needless inner element containers or introducing bloat with JavaScript code – here’s an all-CSS technique for positioning any element with both a proportional offset and a unit offset using only transparent borders.


<div id="my-widget"></div>


#my-widget {
position: absolute;
left: 25%;
border-left: 10px solid transparent;
}

See how I position the div element 25% from the left of the screen + 10 pixels. While margins don’t apply to absolutely positioned elements, the border behaves like an actual part of the element added to the exterior.