There is something oddly fascinating about radio waves, radio communications, and the sheer amount of innovations they've enabled since the end of the 19th century.
What I find even more fascinating is that it is now very easy for anyone to get hands-on experience with radio technologies such as LPWAN (Low-Power Wide Area Network, a technology that allows connecting pieces of equipment over a low-power, long-range, secure radio network) in the context of building connected products.
Let’s explore the complexities of how CSS computes the width and height dimensions of elements. This is based on countless late-night hours debugging and fiddling with lots of combinations of CSS properties, reading though the specs, and trying to figure out why some things seem to behave one way or another.
But before jumping in, let’s cover some basics so we’re all on the same page.
The basics
You have an element, and you want it to be 640px wide and 360px tall. These are just arbitrary numbers that conform to 16:9 pixel ratio. You can set them explicitly like this:
.element {
width: 640px;
height: 360px;
}
Now, the design calls for some padding inside that element. So you modify the CSS:
What is the rendered width and height of the element now? I bet you can guess… it’s not 640×360px anymore! It’s actually 660×380px, because the padding adds 10px to each side (i.e. top, right, bottom and left), for an additional 20px on both the height and width.
This has to do with the box-sizing property: if it’s set to content-box (the default value), the rendered size of the element is the width and height plus the padding and border. That might mean that the rendered size is bigger than we intend which is funny because it might wind up that an element’s declared width and height values are completely different than what’s rendered.
That’s the power of The CSS Box Model. It calculates width and height like so:
What we just saw is how the dimensions for a block element are computed. Block elements include any element that naturally takes up the full width that’s available. So, by nature, it doesn’t matter how much content the element contains because its width is always 100%, that is, until we alter it. Think of elements like <p>, <article>, <main>, <div>, and so many more.
But now we ought to look at inline elements because they behave differently when it comes to The Box Model and how their dimensions are computed. After that, we’ll look at the relationship between parent and child elements, and how they affect the width and height computations of each other.
The curious case of inline elements
As we just saw, the padding and border of any element are both included in the element’s computed width and height dimensions. Funny enough, there are cases where the width and height properties have no effect whatsoever. Such is the case when working with inline elements.
An inline element is an element that’s width and height are determined by the content it contains. Inline elements, such as a <span>, will completely ignore the width and height as well the the left and right margin properties because, well, the content is what determines the dimensions. Here, sometimes a visual can help.
Just look at how nesting a block element inside of an inline element breaks the inline element’s shape simply because the block element is not defined by the amount of content it contains, but rather the amount of available space. You can really see that in action when we add a border to the inline element. Look how the inline element abruptly stops where the paragraph comes in, then continues after the paragraph.
The span sees the paragraph, which interrupts the inline flow of the span and essentially breaks out of it. Fascinating stuff!
But there’s more! Look how the inline element completely overlooks width and margin, even when those are declared right on it.
Crazy!
Parent and child elements
The parent-child relationship is a common pattern. A parent element is one that contains other elements nested inside it. And those nested elements are the parent element’s children.
<!-- The parent element -->
<div class="parent">
<!-- The children -->
<div class="child"></div>
<div class="another-child"></div>
<div class="twins">Whoa!</div>
</div>
The width and height of an element gets super interesting with parent and child elements. Let’s look at all the interesting quirks we get with this.
Relative units
Let’s start with relative units. A relative unit is computed by its context, or relation to other elements. Yeah, that’s sort of a convoluted definition. There are several different types of relative units, but let’s take percentages as an example. We can say that an element is 100% wide.
<div class="child">
<!-- nothing yet -->
</div>
.parent {
width: 100%;
}
Cool. If we plop that element onto an empty page, it will take up 100% of the available horizontal space. And what that 100% computes to depends on the width of the browser, right? 100% of a browser that’s 1,500 pixels is 1,500 pixels wide. 100% of a browser that’s 500 pixels is 500 pixels wide. That’s what we mean by a relative unit. The actual computed value is determined by the context in which it’s used.
So, the astute reader may already be thinking: Hey, so that’s sort of like a child element that’s set to a parent element’s width. And that would be correct. The width of the child at 100% will compute based on the actual width of the parent element that contains it.
Height works much the same way: it’s relative to the parent’s height. For example, two parent elements with different height dimensions but identical children result in children with different heights.
Padding and margin
The width and height of parent-child combinations get even more interesting when we look at other properties, such as padding and margin. Apparently, when we specify a percentage value for padding or margin, it is always relative to the width of the parent, even when dealing with vertical edges.
Some clever designers have taken advantage of it to create boxes of equal width and height, or boxes that keep a certain Aspect ratio when the page resizes. This is particularly useful for video or image content, but can also be (ab)used in creative ways. Go ahead, type whatever you want into the editable element in this demo. The box maintains a proportional height and width, no matter how much (or little) content is added.
This technique for creating Aspect ratio boxes is lovingly referred to as the “padding hack.” Chris has covered it extensively. But now that we have the aspect-ratio property gaining wide browser support, there’s less reason to reach for it.
display: inline and inline-block
Now that we’ve taken looks at how parent and child element dimensions are computed, we should check out two other interesting property values that affect an element’s width: min-content and max-content.
These properties tell the browser to look at the content of the element in order to determine its width. For instance, if we have the text: “hello CSS encyclopedia, nice to meet you!”, the browser would calculate the space that text would take up on the screen, and use it as the width.
The difference between min-content and max-content lies in how the browser does this calculation. For max-content, the browser pretends it has infinite space, and lays all the text in a single line while measuring its width.
For min-content, the browser pretends it has zero space, so it puts every word / child inline element in a different line. Let’s see this in action:
We actually saw max-content in action when we looked at the difference between block and inline elements. Inline elements, remember, are only as wide and tall as the content they contain. We can make most elements inline elements just by declaring display: inline; on it.
Cool. Another weapon we have is display: inline-block;. That creates an inline element, but enhanced with block-level computations in The Box Model. In other words, it’s an inline element that respects margin, width and height. The best of both worlds!
Cyclic percentage size
Did that last point make sense? Well, hopefully I won’t confuse you with this:
The child element in this example has a relative width of 33%. The parent element does not have a width declared on it. How the heck is the child’s computed width get calculated when there’s nothing relative to it?
To answer that, we have to look at how the browser calculates the size of the elements in this example. We haven’t defined a specific width for the parent element, so the browser uses the initial value for width , which is auto. And since the parent element’s display is set to inline-block, auto behaves like max-content. And max-content, as we saw, should mean the parent element is as wide as the content in it, which is everything inside the child element.
So, the browser looks at the element’s content (children) to determine its width. However, the width of the child also depends on the parent’s width! Gah, this is weird!
The CSS Box Sizing Module specification calls this cyclic percentage sizing. I’m not sure why it’s called that exactly, but it details the complex math the browser has to do to (1) determine the parent element’s width, and (2) reconcile that width to the relative width of the child.
The process is actually pretty cool once you get over the math stuff. The browser starts by calculating a temporary width for the child before its declared value is applied. The temporary width the browser uses for the child is auto which we saw behaves like max-content which, in turn, tells the browser that the child needs to be as wide as the content it contains. And right now, that’s not the declared 33% value.
That max-content value is what the browser uses to calculate the parent’s width. The parent, you see, needs to be at least as wide as the content that it contains, which is everything in the child at max-content. Once that resolves, the browser goes back to the child element and applies the 33% value that’s declared in the CSS.
This is how it looks:
There! Now we know how a child element can contribute to the computed value of its parent.
M&Ms: the min- and max- properties
Hey, so you’re probably aware that the following properties exist:
min-width
min-height
max-width
max-height
Well, those have a lot to do with an element’s width and height as well. They specify the limits an element’s size. It’s like saying, Hey, browser, make sure this element is never under this width/height or above this width/height.
So, even if we have declared an explicit width on an element, say 100%, we can still cap that value by giving it a max-width:
element {
width: 100%;
max-width: 800px;
}
This allows the browser to let the element take up as much space as it wants, up to 800 pixels. Let’s look what happens if we flip those values around and set the max-width to 100% and width to 800px:
element {
width: 800px;
max-width: 100%;
}
Hey look, it seems to result in the exact same behavior! The element takes up all the space it needs until it gets to 800 pixels.
Apparently, things start to get more complex as soon as we add a parent element into the mix. This is the same example as above, with one notable change: now each element is a child of an inline-block element. Suddenly, we see a striking difference between the two examples:
Why the difference? To understand, let’s consider how the browser calculates the width of the elements in this example.
We start with the parent element (.parent). It has a display property set to inline-block, and we didn’t specify a width value for it. Just like before, the browser looks at the size of its children to determine its width. Each box in this example is wrapped in the .parent element.
The first box (#container1) has a percentage width value of 100%. The width of the parent resolves to the width of the text within (the child’s max-content), limited by the value we specified by max-width, and that is used to calculate the width of the child as well.
The second box (#container2) has a set width of 800px, so its parent width is also 800px — just wide enough to fit its child. Then, the child’s max-width is resolved relative to the parent’s final width, that is 800px. So both the parent and the child are 800px wide in this case.
So, even though we initially saw the two boxes behave the same when we swapped width and max-width values, we now know that isn’t always true. In this case, introducing a parent element set to display: inline-block; threw it all off!
min(): Returns the minimum value of its arguments. The arguments can be given in different units, and we can even mix and match absolute and relative units, like min(800px, 100%).
max(): Returns the maximum value of its arguments. Just like min(), you can mix and match different units.
clamp(): A shorthand function for doing min and max at once: clamp(MIN, VAL, MAX) is resolved as max(MIN, min(VAL, MAX)). In other words, it will return VAL, unless it exceeds the boundaries defined by MIN and MAX, in which case it’ll return the corresponding boundary value.
Like this. Check out how we can effectively “re-write” the max-width example from above using a single CSS property:
That would set the width of the element to 800px, but make sure we don’t exceed the width of the parent (100%). Just like before, if we wrap the element with an inline-block parent, we can observe it behaving differently than the max-width variation:
The width of the children (800px) is the same. However, if you enlarge the screen (or use CodePen’s 0.5x button to zoom out), you will notice that the second parent is actually larger.
It boils down to how the browser calculates the parent’s width: we didn’t specify a width for the parent, and as child’s width value is using relative units, the browser ignores it while calculating the parent’s width and uses the max-content child of the child, dictated by the “very long … long” text.
Wrapping up
Phew! It’s crazy that something as seemingly simple as width and height actually have a lot going on. Sure, we can set explicit width and height values on an element, but the actual values that render often end up being something completely different.
That’s the beauty (and, frankly, the frustration) with CSS. It’s so carefully considered and accounts for so many edge cases. I mean, the concept of The Box Model itself is wonderfully complex and elegant at the same time. Where else can we explicitly declare something in code and have it interpreted in different ways? The width isn’t always the width.
And we haven’t even touched on some other contributing factors to an element’s dimensions. Modern layout techniques, like CSS Flexbox and Grid introduce axes and track lines that also determine the rendered size of an element.
Font-size: An Unexpectedly Complex CSS Property — From Manish Goregaokar in 2017. Of many oddities, I found the one where font: medium monospace renders at 13px where font: medium sans-serif renders at 16px particularly weird.
The good line-height — Since CSS supports unitless line-height, you probably shouldn’t be setting a hard number anyway.
Time to Say Goodbye to Google Fonts — Simon Wicki doesn’t mean don’t use them, they mean self-host them. Browsers are starting to isolate cache on a per-domain basis so that old argument that you buy speed because “users probably already have it cached” doesn’t hold up. I expected to hear about stuff like having more control over font loading, but this is just about the cache.
My Favorite Typefaces of 2020 — John Boardley’s picks for the past year. Have you seen these “color fonts”? They are so cool. Check out LiebeHeide, it looks like real pen-on-paper.
How to avoid layout shifts caused by web fonts — We’ve got CLS (Cumulative Layout Shift) now and it’s such an important performance metric that will soon start affecting SEO. And because we have CSS control over font loading via font-display, that means if we set things up such that font loading shifts the page, that’s bad. I like Simon Hearne’s suggestion that we tweak both our custom font and fallback font to match perfectly. I think perfect fallback fonts are one of the best CSS tricks.
How to pick a Typeface for User Interface and App Design? — Oliver Schöndorfer makes the case for “functional text” which is everything that isn’t body text (e.g. paragraphs of text) or display text (e.g. headers). “Clarity is key.”
While there are dozens of great tools for building a website, Wix offers the fastest route to a complete and fully-functioning site. With AI-powered tools like the Wix ADI (Artificial Design Intelligence), you can enjoy a hands-off website building experience without sacrificing your personal touch. In this Wix tutorial, we will guide you through building a website from start to finish.
Dell Inspiron is stuck in Network update configuration boot loop will not go into to set up or bios. Hard drive has been erased need to reinstall Windows 10 how do I get it to stop Network booting?
Apple has announced several updates to its App Store Review Guidelines that portend forthcoming changes to the platform. These guidelines include mention of a new App Tracking Transparency feature which has been long rumored as an attempt to improve platform privacy.
One was the footer of an (older) U.S. Government website:
The other was the navigation for AWS services from the AWS Console:
Both of them have that vibe of: holy crap we have a lot of stuff, I guess we’ll just make a massive grid of links to it all.
The difference is the AWS Console one has a search bar at the top of it. Its primary function is finding things in that menu (but it does search the wider site as well):
The “search a list of things already on the page” idea reminds me of that classic jQuery contains selector. Please allow me:
Even the smallest of vulnerabilities on your WordPress site can be easily exploited by hackers and used to hijack your entire website. This can cause severe damage through the actions of stealing data, sending spam, or even defacing pages. That’s also not to mention that you risk having your site blacklisted by Google if it’s […]
The next major release of WordPress will make it much easier for users to migrate their sites from HTTP to HTTPS. It introduces new capabilities to detect if the user’s hosting environment has support for HTTPS and provides a one-click update process, handling mixed content rewrites where possible.
“A major pain point in WordPress has been the migration of a WordPress site from HTTP to HTTPS: While changing the Site Address and WordPress Address to use HTTPS is trivial, updating references to the old URLs in existing content is not,” WordPress Core Committer Felix Arntz said in the ticket proposing the feature. “It cannot be accomplished within core UI and requires use of more advanced tools, such as WP-CLI or plugins like Better Search Replace, which is a no-go for most users.”
In WordPress 5.6, there is no clear guidance in the Site Health screen about how to migrate to HTTPS, even though it shows as an issue. The user would need to learn more about how to update it manually, starting with changing the site URLs.
In WordPress 5.7, if HTTPS is supported, the Site Health Status screen will notify users and guide them with a new button that updates the site with a single click. It also migrates the site content on the fly to use HTTPS for URLs. Arntz recorded a video demo of the update:
This change also comes with new environment variables and filters that allow hosting providers to change the URLs linked in the HTTPS status check in Site Health, so they can more effectively manage it for their customers’ hosting options. This is similar to how hosts can modify URLs for updating the PHP version, which has had a positive impact on getting sites running on supported versions of PHP.
It’s important to note that the streamlined HTTP to HTTPS migration in 5.7 does not handle updating content in the database. Also, if a site’s URLs are controlled by constants, the update is not possible to complete automatically. In these instances, the HTTPS status check on the Site Health screen will inform the user why the site would need to be manually updated.
More technical details are available in the ticket and commit message, and a dev note should be forthcoming.
Volvo Cars has announced an all-new open data platform that provides developers and researchers with access to valuable resources pertaining to automobile data, LiDAR specifications, and more. The Volvo Cars Innovation Platform is free for non-commercial use.
A membership website is a great business model. Many WordPress users have realized big profits by offering memberships on their websites. And it’s not only the little guy having all the fun. Big brands, too, are making a killing. A great example is Amazon Prime, which makes over $19 billion annually. Costco reportedly makes about […]
This is the February 2021 edition of “This Month in WordPress with CodeinWP.” Hey, everyone! We hope this year has been going great for you all so far. We’re back with a new edition of the WordPress news to let you know how the first month of the year went for WordPress.
There was a time when billing customers was a cut and dry situation. A monthly statement was sent to a customer via snail-mail, and a check was written and shipped back to the payee. But like other industries, the billing industry has undergone a digital transformation.