CSS px
Created By: chatGPT
CSS uses various units for measuring length and size. One common unit is pixels (px), which is a fixed unit that represents a single dot on the screen. This means that when you set the size of an element in pixels, it will remain the same size regardless of the screen resolution or size, making it a predictable choice for layout purposes.
body {
font-size: 16px;
padding: 20px;
}
h1 {
font-size: 24px;
}
p {
line-height: 1.5;
}
.container {
width: 800px;
margin: 0 auto;
}
When using px, you may want to ensure that your layout is responsive. To achieve this, you can use other relative units like em and rem alongside px for better scalability on different devices.
body {
font-size: 16px;
}
h1 {
font-size: 2rem; /* This is 32px if 1rem = 16px */
}
p {
font-size: 1em; /* This is equal to the font-size of the body */
}
.container {
width: 80%; /* relative to the viewport width */
}
To convert between px and em/ rem, remember that:
- 1 em = current font size
- 1 rem = root font size (typically the html element).
This conversion is helpful when you want to maintain scalability and accessibility in your designs.
/* Example of rem usage */
html {
font-size: 100%; /* usually equals 16px */
}
h2 {
font-size: 1.5rem; /* 24px */
}
.button {
padding: 10px 20px;
font-size: 1rem; /* 16px */
}