rem and em are two special units that allow us to control the size consistently in different positions, supporting the creation of a responsive interface in a simple way.
rem is short for "root em". This unit is calculated based on the size of the root element of the web page. Typically, the root element will be the <html> tag. When using rem, its value will change based on the size of the root element.
For example, if you set the size of the root element to 16px, a rem value of 1 will be equivalent to 16px. If you want to set the size of an element to be twice the size of the root element, you can use a rem value of 2.
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* KÃch thÆ°á»›c font chÃnh xác là 32px */
}
p {
font-size: 1.5rem; /* KÃch thÆ°á»›c font chÃnh xác là 24px */
}
em is a measurement unit similar to rem, but it is based on the size of the parent element. If the parent element has a font size of 16px and the child element has an em value of 2, the font size of the child element will be 32px.
.parent {
font-size: 16px;
}
.child {
font-size: 2em; /* KÃch thÆ°á»›c font chÃnh xác là 32px */
}
Although rem and em can both help us create responsive interfaces, they have some important differences:
To make the most of rem and em in creating a responsive interface, you can use them in properties such as font size, padding, margin, etc.
.container {
font-size: 1.5rem; /* KÃch thÆ°á»›c font chÃnh xác là 24px */
padding: 2rem; /* Padding chÃnh xác là 32px */
}
.button {
font-size: 1.2em; /* KÃch thÆ°á»›c font chÃnh xác là 19.2px */
margin-bottom: 1.5em; /* Margin chÃnh xác là 24px */
}
When using rem and em, you can ensure that your interface will adapt to different screen sizes. It helps increase consistency and uniformity across the entire website.