CSS Data Type - <percentage>
The CSS <percentage> data type represents a proportion of another value, typically relative to the parent element or some other reference value. Percentages are often used in various CSS properties (such as font-size, width, height, margin, and padding) to specify dimensions, spacing, or other proportional values.
Syntax
<number>%
A <number> and the percentage symbol (%) come together to form the <percentage> data type. A single + or - sign is an optional way to start it, albeit not all properties allow negative values. Unlike other dimension kinds, CSS dimensions do not have a gap between the symbol and the number.
CSS <percentage> - Sizing Font
The following example demonstrates the usage of <percentage> datatype to size the font.
<html> <head> <style> body, html { margin: 0; padding: 0; } .container { width: 90%; /* Set container width to 90% of the viewport width */ background-color: #f0f0f0; margin: 40px auto; } .text { font-size: 100%; /* Default font size (16px) */ text-align: center; margin: 20px 0; } .text-smaller { font-size: 80%; /* Font size 80% of the default size */ color: red; } .text-larger { font-size: 120%; /* Font size 120% of the default size */ color: blue; } </style> </head> <body> <div class="container"> <p class="text">Font Size with Percentage</p> <p class="text text-smaller">Smaller Font Size</p> <p class="text text-larger">Larger Font Size</p> </div> </body> </html>
CSS <percentage> - Sizing A Box
The following example demonstrates the usage of <percentage> datatype to alter the size of container and box.
<html> <head> <style> body, html { margin: 0; padding: 0; } .container { width: 70%; /* Set container width to 70% of the viewport width */ margin: 20px auto; background-color: #f4f4f4; padding: 20px; } .box { width: 40%; /* Box width set to 40% of its container */ height: 200px; background-color: #3498db; color: white; text-align: center; line-height: 200px; margin: 0 auto 20px; } .box:nth-child(2) { width: 60%; /* Box width set to 60% of its container */ height: 160px; background-color: #e74c3c; line-height: 160px; } </style> </head> <body> <div class="container"> <div class="box"> <p>Box 1 - 40% of container width</p> </div> <div class="box"> <p>Box 2 - 60% of container width</p> </div> </div> </body> </html>
To Continue Learning Please Login
Login with Google