HTML SVG Basics Introduction to SVG SVGs as Images

Vince Varga
Vince Varga
15,280 Points

Why doesn't using px and % values at the same time mess up the site?

In this video px and % percentage values are both used to set margin and width. I do not understand why using them at the same time doesn't mess up when changing the size of the window.

3 Answers

Nick Pettit
STAFF
Nick Pettit
Treehouse Teacher

Every page element has a "computed" value, expressed in pixels. Relative units are converted into pixels on-the-fly, so even though the CSS might say something like 50%, the browser will convert that to pixels behind-the-scenes.

As the browser window is resized, the computed value changes automatically. Let's say a <div> has a width of 50% and the browser window is 1000px wide. The <div> will have a computed value of 500px. If the browser window is resized to 800px wide, the computed value of the <div> will become 400px.

Computed values are a great way of figuring out weird styling bugs. In the Google Chrome web browser, you can right click on an element and choose "Inspect Element". This will bring up the Chrome Dev Tools, and on the right side you should see a tab labeled "Computed". Clicking this tab will show you the computed values for the given element, including the computed width and height, computed margin, computed padding, and so on.

Juliana Madrone
Juliana Madrone
8,552 Points

Hi, I'm not sure exactly how the margin and width are being set in your video, but there are cases where that works. For instance, if the margin of certain elements or of the body of the page is set to pixels, this means it will be the same no matter how the page size changes. Setting the width to a percentage will allow the body of the webpage to adjust with the window size while keeping those margins at the exact pixel size. Hope that helps in your specific case!

Wayne Priestley
Wayne Priestley
19,565 Points

Hi Vince,

Your using values that the browser is smart enough to interpret, at the end of the day they are all the same value no matter how they are expressed. For example, if a browser is 1000px wide the following code is all the same.

.img {
width: 500px;
}

.img {
width: 50%;
}

.img {
width: 31.25em;
}

.img {
width: 31.2rem;
}

They all mean the same thing to the browser, so we can mix and match as much as we want and get the same results.

Hope this helps.

Vince Varga
Vince Varga
15,280 Points

But what happens when you resize the browser window? I mean I know what happens, but I don't understand why.