What does the CSS Unit Converter (px to rem / em / %) do?
The CSS Unit Converter converts absolute pixel measurements (px) into relative stylesheet units (rem, em, %, pt) based on a configurable root font size (default 16px). It operates in two modes: converting standalone numeric values for quick reference, or bulk-replacing every pixel value inside full CSS stylesheets while preserving selectors and properties.
Core Concepts
Understanding responsive CSS typography units ensures accessible web design:
- Root EM (
rem): Relative to the root<html>font size (default16px), so24pxbecomes1.5rem. Unlikeem,remdoes not compound when nested inside parent elements. - Element EM (
em): Relative to the immediate parent element's font size, useful for component padding and margin proportions that scale with local font size. - Percentage (
%): Expresses size relative to the base font size, where16pxequals100%. - Points (
pt): Traditional typography print unit where1pt = 1/72 inch($1\text{px} = 0.75\text{pt}$).
How to use the tool?
- Enter Pixel Value or Stylesheet: Input a single number (e.g.
24) or paste full CSS declarations (e.g.font-size: 24px; padding: 16px 32px;). - Configure Settings:
- Set Target Unit (
rem,em,%,pt,px). - Configure Base Root Font Size (default
16px).
- Set Target Unit (
- Execute & Copy: Click Convert CSS Units to get clean relative values and copy the output directly.
Related Developer Utilities
If you are styling interfaces, writing stylesheets, or building responsive web layouts, explore these related tools:
- CSS Formatter & Beautifier: Clean and re-indent messy CSS stylesheets.
- CSS Minifier: Strip comments and whitespace to optimize production stylesheet byte size.
- HTML Syntax Validator: Inspect markup for unclosed tags and syntax errors.
- HTML Entity Encoder: Encode reserved characters into named and numeric HTML entities.
REST API Integration
Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/css/css-unit-converter) to programmatically convert CSS pixel values (px) to rem, em, %, or pt units for numeric values or full CSS stylesheets.
API Request Parameters
| Name | Type | Description | Example |
|---|---|---|---|
inputVal |
String/Number | Pixel numeric value or CSS code string. | "font-size: 24px;" |
options.targetUnit |
String | Target unit ("rem", "em", "%", "pt"). Defaults to "rem". |
"rem" |
options.basePx |
Number | Base root font size in pixels. Defaults to 16. |
16 |
API Request Payload Examples
cURL
curl -X POST https://blueutils.com/api/css/css-unit-converter \
-H "Content-Type: application/json" \
-d '{
"inputVal": "font-size: 24px; padding: 16px;",
"options": { "targetUnit": "rem", "basePx": 16 }
}'Python
import requests
url = "https://blueutils.com/api/css/css-unit-converter"
payload = {
"inputVal": "font-size: 24px; padding: 16px;",
"options": {"targetUnit": "rem", "basePx": 16}
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String jsonPayload = """
{
"inputVal": "font-size: 24px; padding: 16px;",
"options": { "targetUnit": "rem", "basePx": 16 }
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://blueutils.com/api/css/css-unit-converter"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}API Response Parameters
| Name | Type | Description | Example |
|---|---|---|---|
isValid |
Boolean | Indicates whether the conversion succeeded. | true |
convertedValue |
String | Converted CSS value or stylesheet text. | "font-size: 1.5rem; padding: 1rem;" |
numericValue |
Number | Converted numeric scalar value (when input is numeric). | 1.5 |
basePx |
Number | Base root font size used for calculation. | 16 |
API Response Payload Examples
Success Response (HTTP 200 OK)
{
"isValid": true,
"convertedValue": "font-size: 1.5rem; padding: 1rem;",
"result": "font-size: 1.5rem; padding: 1rem;",
"basePx": 16
}Validation Failure Response (HTTP 400 Bad Request)
{
"isValid": false,
"error": "Invalid input: CSS value or code payload cannot be empty."
}Rate Limit Exceeded Response (HTTP 429 Too Many Requests)
{
"error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}Why use an API to convert CSS units?
Integrating the CSS Unit Converter API into design system tools, CSS pre-processors, or headless build scripts provides several advantages:
- Rapid Script Validation: Enables automated build scripts to standardize arbitrary design token pixel exports into consistent rem values across web components.
- Optimized Token Efficiency for AI Agents: Offloads floating-point unit math and regex CSS token substitution to an external endpoint with zero prompt reasoning cost.
- Deterministic Accuracy Without Hallucinations: Ensures exact arithmetic division and decimal formatting without rounding errors or corrupted CSS syntax.
Native Usage
How to convert CSS pixel values to relative units locally in your terminal or scripts:
Windows (CMD / PowerShell)
# Convert pixels to rem in PowerShell
$base = 16
(Get-Content style.css) -replace '(\d+)px', { [math]::Round([double]$args[0].Groups[1].Value / $base, 4).ToString() + 'rem' }Linux / Unix (Bash)
# Convert pixel units in CSS files using sed/awk
awk '{for(i=1;i<=NF;i++) if($i ~ /[0-9]+px/) {sub(/px/,"",$i); $i=($i/16)"rem"} print}' style.cssPython
Using Python standard library re:
import re
base_px = 16
css = "font-size: 24px; padding: 16px 32px;"
converted = re.sub(r'(\d+(?:\.\d+)?)px', lambda m: f"{float(m.group(1))/base_px:g}rem", css)
print(converted)Java
Using Java regex replacement:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CssUnitConverter {
public static void main(String[] args) {
String css = "font-size: 24px; margin: 16px;";
double basePx = 16.0;
Pattern pattern = Pattern.compile("(\\d+)px");
Matcher matcher = pattern.matcher(css);
String result = matcher.replaceAll(mr -> (Double.parseDouble(mr.group(1)) / basePx) + "rem");
System.out.println(result);
}
}