In LESS CSS, calculating percentages can be achieved using LESS's built-in functions, with the percentage() function being the most commonly used. This function converts a decimal value into a percentage format, which is highly useful for handling dynamic style calculations—such as adjusting the width of internal elements based on the container's size.
Example
Assume you have a container with a dynamic width, and you want to set the width of a child element to 50% of the container's width. In LESS, you can do this:
less@container-width: 100%; // Assume the container width is 100% .child-width { width: percentage(0.5); // Calculate the width as 50% }
In this code, percentage(0.5) evaluates to 50%, ensuring the child element's width remains 50% of the container's width regardless of changes to the container's size.
More Complex Example
If you want to dynamically calculate percentages based on other variables, it is possible. For example, consider two variables: one for the container's width and one for the child element's proportion:
less@container-width: 80%; // Assume the container width is 80% @part: 0.3; // Child element occupies 30% of the container .child { width: percentage(@part); // Calculate percentage based on @part variable }
Here, percentage(@part) evaluates to 30%, so the child element's width is 30% of the container's width.
In this way, LESS provides flexible methods for handling styles, especially in responsive layouts or dynamic style adjustments. This approach simplifies complex CSS computations, making the code more maintainable and understandable.