惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Securelist
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Last Watchdog
The Last Watchdog
S
Schneier on Security
T
Troy Hunt's Blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Schneier on Security
Schneier on Security
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog
T
Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
Arctic Wolf
S
Secure Thoughts
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
Security Archives - TechRepublic
Security Archives - TechRepublic
Latest news
Latest news
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
GRAHAM CLULEY
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
Webroot Blog
Webroot Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog

Ahmad Shadeed

Better fluid sizing with round() Use Cases for Field Sizing The Basics of Anchor Positioning Item Flow CSS Relative Colors Balancing Text In CSS Should masonry be part of CSS grid? CSS display contents CSS Grid Areas CSS Cap Unit An Interactive Guide to CSS Container Queries CSS :has() Interactive Guide CSS Nesting UX in DevTools CSS Nesting Future CSS: State Container Queries Rebuilding a comment component with modern CSS Conditional CSS with :has and :nth-last-child CSS Text balancing with text-wrap:balance CSS Masking Do we need CSS flex-wrap detection? My CSS Wishlist Conditional CSS CSS Style Queries Inside the mind of a frontend developer: Article layout Inside the mind of a frontend developer: Hero section CSS container queries are finally here The CSS behind Figma First Look At The CSS object-view-box Property Learn CSS Subgrid CSS :has Parent Selector Flexbox Dynamic Line Separator Hello, CSS Cascade Layers Building UI Components With SVG and CSS A Deep CSS Dive Into Radial And Conic Gradients Defensive CSS Building Real-life Components: Facebook Messenger Conditional Border Radius In CSS CSS Container Query Units Less Absolute Positioning With Modern CSS Aligning a Button Label Vertically Comparing Design Mockups To Code Result Using HSL Colors In CSS Custom Scrollbars In CSS Let CSS Container Queries For Designers The State of CSS Cross-Browser Development Overflow Issues In CSS Inspect Element As A Way To Increase Your Curiosity Handling Text Over Images in CSS Digging Into CSS Logical Properties Clipping Scrollable Areas On The inline-start Side Understanding Clip Path in CSS The Art of Building Real-life Components Handling Short And Long Content In CSS CSS Scroll Snap A Deep Dive Into CSS Grid minmax() CSS Variables 101 Finding The Root Cause of a CSS Bug Learn CSS centering How to detect browser support for Flexbox Gap CSS Mistakes While On Autopilot Digging Into the Flex Property Understanding CSS Multiple Backgrounds Aligning Logo Images in CSS Grid for layout, Flexbox for components Colors in CSS Thinking About The In-between Design Cases min(), max(), and clamp() CSS Functions Image Techniques On The Web Everything About Auto in CSS Learn Box Alignment Let Learn CSS Positioning Intrinsic Sizing In CSS CSS Grid Template Areas In Action Hiding Elements On The Web Creating a Variable Color Font From Scratch Building a Football Ticket With CSS and SVG Blending Modes in CSS CSS Variables With Inline Styles Implementing Dark Mode For My Website Rebuilding Apple Music Header in HTML & CSS Accessible Checkbox Layout Flickering On Browser Resize Enhancing The Clickable Area Size Custom Underlines with SVG Part 3: The Process of Implementing A UI Design From Scratch Part 2: The Process of Implementing A UI Design From Scratch Building An Old Nav Design CSS Flexbox: 5 Real World Use Cases I Used CSS Inline Flex For The First Time The Process of Implementing A UI Design From Scratch Common CSS Issues For Front-End Projects Handling Long and Unexpected Content in CSS How to Build Web Form Layouts With CSS Grid Grid Layout Ah-ha Moment Enhancing Our Components with CSS :empty Building Resizeable Components with Relative CSS Units CSS Writing Mode The Journey of Learning Front End Web Development on a Daily Basis
Aligning Content In Different Wrappers
Ahmad Shadeed · 2022-03-14 · via Ahmad Shadeed

The Layout Maestro

I spent years teaching CSS layout on this blog. I put everything I know into The Layout Maestro course: 70+ lessons and 150+ interactive examples that teach you how to think CSS layouts, not just memorize syntax.

Get the course

The other day, I was working on an article layout and I stumbled upon an interesting problem to solve. Here it is:

As you see, we have the following:

  • Main header: logo and navigation
  • Article header: headline and teaser
  • Body content

The main header is wrapped with a fixed-width element that is centered horizontally.

<header class="site-header">
  <div class="wrapper">
    <!-- Header content -->
  </div>
</header>
.wrapper {
  max-width: 1100px;
  margin-left: auto;
  margin-right: auto;
  padding-left: 1rem;
  padding-right: 1rem;
}

For the article header, it’s not wrapped into anything and lives on its own.

<header class="site-header">
  <div class="wrapper">
    <!-- Header content -->
  </div>
</header>
<div class="article-header">
  <h1><!-- Title --></h1>
  <p>!-- Description --></p>
</div>

The problem here lies in the article header. If you notice in the figure above, it has left padding that makes it aligned with where the logo starts. At first, it seems doable, but you will change your mind when resizing the screen.

In the following figure, the screen size got larger. Notice how the article header isn’t aligned with the logo.

When the screen size is smaller, the issue will also happen.

To recap, the problem we’re trying to solve here is to have a padding-left value that is dynamic based on the space from the left edge of the screen to the start of the content wrapper.

Consider the following figure. The main header and body content are both wrapped into a fixed-width element, but the article header is not. What we want to achieve is a dynamic padding value for the article header.

To achieve that, we need to do some math. Here it is in plain words:

dynamic padding = (viewport width - wrapper width) / 2

Let’s take the following example.

Given the values we have, here is the dynamic padding value:

dynamic padding = (1300 - 1100) / 2 = 100

You might be wondering, why divide by 2? Well, because we have dynamic areas on both left and right, we only need one side.

The solution

In CSS, we will use the following to achieve the above:

  • Viewport units
  • calc() function
  • max() comparison function
  • CSS variables

We can use the value 100vw to get the full width of the viewport

.article-header {
  padding-left: calc(100vw - calc(1100px / 2));
}

That way, the value of the padding-left will be dynamic and will make the article header content aligned with the logo and navigation.

Though, we’re not finished. We need to account for the .wrapper horizontal padding.

.article-header {
  padding-left: calc(100vw - calc(1100px / 2) - 32px);
}

The 32px is the sum of the left and right padding.

Handling the padding on mobile

Since we subtracted the padding value from the wrapper, the article header padding will be zero on mobile.

To revert the padding back, we need to get help from the CSS max() function. The goal is to give it a minimum value for the padding.

.article-header {
  padding-left: max(1rem, calc(100vw - calc(1100px / 2) - 32px));
}

That way, the horizontal padding will be at least 1rem, and will become dynamic when the viewport size gets larger.

You can learn more about max() and its friend in this article by yours truly.

Using CSS variables

To make things even more abstract, we can add all the above within one CSS variable so we can use it in different places.

:root {
  --wrapper-width: 1100px;
  --wrapper-padding: 16px;
  --space: max(
    1rem,
    calc(
      (
          100vw - calc(var(--wrapper-width) - var(--wrapper-padding) *
                2)
        ) / 2
    )
  );
}

.article-header {
  padding-left: var(--space);
}

The only issue with 100vw

On Mac OS, the scrollbars aren’t visible by default unless the user chose that from the system preferences. If the scrollbars are visible by default, the 100vw will be equal to 100% of the viewport width minus the scrollbar width. This will cause a misalignment issue.

Since the element doesn’t live in a wrapper, we can replace the 100vw with 100% instead, and it will work as expected.

:root {
  --wrapper-width: 1100px;
  --wrapper-padding: 16px;
  --space: max(
    1rem,
    calc(
      (100% - calc(var(--wrapper-width) - var(--wrapper-padding) * 2)) /
        2
    )
  );
}

.article-header {
  padding-left: var(--space);
}

UppubDate: 15 March 2022

Dannie Vinther reminded me that max() will do the math without the need of the calc() function. Neat!

:root {
  --space: max(
    1rem,
    100% - (var(—wrapper) - ((var(—wrapper-padding) * 2) / 2))
  );
}

See the Pen Untitled by Ahmad Shadeed (@shadeed) on CodePen.

That’s it for this little CSS trick. I hope you’ve learned something new!