CSS Unit Converter
Convert between px, em, rem, vw, vh, pt, and cm for responsive web design.
Settings
Frequently Asked Questions
Code Implementation
# CSS unit conversions in Python
BASE_FONT_SIZE = 16 # px (browser default)
def px_to_rem(px: float, base: float = BASE_FONT_SIZE) -> float:
"""Convert px to rem (relative to root font size)."""
return px / base
def rem_to_px(rem: float, base: float = BASE_FONT_SIZE) -> float:
return rem * base
def px_to_em(px: float, parent_font_size: float) -> float:
"""Convert px to em (relative to parent font size)."""
return px / parent_font_size
def px_to_vw(px: float, viewport_width: float) -> float:
"""Convert px to vw units given a viewport width."""
return (px / viewport_width) * 100
def px_to_vh(px: float, viewport_height: float) -> float:
return (px / viewport_height) * 100
# Examples
print(px_to_rem(24)) # 1.5 (24px / 16 = 1.5rem)
print(rem_to_px(1.5)) # 24.0
print(px_to_em(18, 16)) # 1.125 (18px relative to 16px parent)
print(px_to_vw(320, 1440)) # 22.222...vw
print(px_to_vh(100, 900)) # 11.111...vh
# Batch convert a list of px values to rem
px_values = [12, 14, 16, 18, 20, 24, 32, 48]
for px in px_values:
print(f"{px}px = {px_to_rem(px):.4f}rem")Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.