我面临一个具有挑战性的 CSS 布局问题,需要帮助。我的目标是在容器中拥有一个始终跟随水平滚动的标题,但仅在存在垂直滚动时才跟随垂直滚动。
容器将包含多个不同高度的文档。一个关键要求是容器不应扩展到最高文档的高度,这会增加任务的复杂性。
具体要求:
问题:
对此的任何指导或建议将不胜感激!
这是我到目前为止所探索的内容:
基于设置 => https://codepen.io/samuelclo/pen/poYorbv?editors=1100
或者 => https://github.com/samuelClo/test-overflow/tree/main
const getScrollbarWidth = () => {
// Creating invisible container
const outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.overflow = "scroll"; // forcing scrollbar to appear
// @ts-expect-error needed for WinJS apps
outer.style.msOverflowStyle = "scrollbar";
document.body.appendChild(outer);
// Creating inner element and placing it in the container
const inner = document.createElement("div");
outer.appendChild(inner);
// Calculating difference between container's full width and the child width
const scrollbarWidth = outer.offsetWidth - inner.offsetWidth;
// Removing temporary elements from the DOM
outer.parentNode?.removeChild(outer);
return scrollbarWidth;
};
document.documentElement.style.setProperty(
"--scrollbar-width-js",
getScrollbarWidth() + "px"
);
:root {
--common-width: 300px;
--scrollbar-width: var(--scrollbar-width-js, 12px)
}
html,
body {
margin: 0;
padding: 0;
font-family: system-ui, sans-serif;
}
.card {
width: var(--common-width);
border-radius: 10px;
padding: 15px 25px;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.02), 0 0 0 1px rgba(27, 31, 35, 0.15);
}
header {
top: 0;
margin: 20px auto;
}
main {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
/* Use to define a height because if all child is exclude from the DOM there is no height min-height: 100vh; */
min-height: 100vh;
}
.l-include-gutter {
flex-shrink: 0;
width: 100%;
scroll-snap-align: center;
/* Pretty recent */
/* https://caniuse.com/?search=contain */
contain: size;
/* Add scroll bar width */
scrollbar-gutter: stable;
overflow-y: scroll;
/* Because child has a more than 100% width */
overflow-x: clip;
}
.l-article {
width: calc(100% + var(--scrollbar-width));
display: flex;
flex-direction: column;
align-items: center;
}
/* For safari */
/* https://caniuse.com/mdn-css_properties_scrollbar-gutter */
@supports not (scrollbar-gutter: stable) {
.l-article {
overflow-y: scroll;
}
}
<header class="card">
<h2>
Exploring Transformation: Artificial Intelligence and Climate Change
</h2>
<p>
Delve into two distinct yet interconnected realms of human innovation
and global concern. First, journey through the evolution of Artificial
Intelligence (AI) as it progresses from its mid-20th-century inception
to the transformative technology it is today. Discover how AI has
revolutionized industries, healthcare, and decision-making, while also
posing challenges like job displacement and bias.
</p>
</header>
<main>
<div class="l-include-gutter">
<div class="l-article">
<button>Click on me !</button>
<article class="card">
<h3>Climate change</h3>
<p>
Climate change is one of the most pressing issues facing humanity
today. It refers to long-term changes in global temperature and
weather patterns, primarily driven by human activities such as the
burning of fossil fuels, deforestation, and industrial processes.
</p>
</article>
</div>
</div>
<div class="l-include-gutter">
<div class="l-article">
<button>Click on me !</button>
<article class="card">
<h3>The Evolution of Artificial Intelligence</h3>
<p>
Artificial Intelligence (AI) has come a long way since its
inception in the mid-20th century. The term "artificial
intelligence" was first coined by John McCarthy in 1956 during a
Dartmouth College workshop. Early AI research focused on symbolic
reasoning and rule-based systems, but progress was slow due to
limited computing power.
</p>
<p>
In the 21st century, AI entered a new era, thanks to advancements
in machine learning and neural networks. Deep learning, a subset
of machine learning, made it possible for computers to process
vast amounts of data and perform complex tasks. This breakthrough
paved the way for the development of AI systems that could
understand natural language, recognize images, and even beat human
champions in games like chess and Go.
</p>
<h3>Applications of AI Across Industries</h3>
<p>
AI has revolutionized healthcare by improving diagnosis,
treatment, and patient care. Machine learning algorithms can
analyze medical images, such as X-rays and MRI scans, to detect
abnormalities and assist radiologists in making accurate
diagnoses. Additionally, AI-driven chatbots and virtual nurses are
enhancing patient engagement and monitoring.
</p>
<p>
In the financial industry, AI is used for algorithmic trading,
fraud detection, credit risk assessment, and customer service.
AI-powered robo-advisors provide personalized investment
recommendations, while natural language processing enables
sentiment analysis of news and social media for trading decisions.
</p>
<p>
AI is transforming education through personalized learning
platforms that adapt to students' needs and abilities. Intelligent
tutoring systems provide instant feedback and tailored exercises,
enhancing student performance. Furthermore, AI-driven analytics
help educators identify at-risk students and implement timely
interventions.
</p>
<p>
Automation and robotics have long been associated with
manufacturing, but AI is taking these technologies to the next
level. AI-driven robots can perform complex tasks with precision,
reducing errors and increasing efficiency. Predictive maintenance
powered by AI minimizes equipment downtime, saving companies
millions.
</p>
<p>
The transportation sector is experiencing a seismic shift with
AI-driven autonomous vehicles. Companies like Tesla and Waymo are
developing self-driving cars that promise safer and more efficient
transportation. AI also optimizes traffic management, reducing
congestion and emissions.
</p>
<p>
AI has made its mark in the entertainment industry through content
recommendation systems like Netflix's recommendation algorithm.
Additionally, AI-generated art and music are gaining recognition
in the creative world, blurring the lines between human and
machine creativity.
</p>
<h3>Benefits of AI</h3>
<p>AI offers numerous benefits, including:</p>
<ul>
<li>
Efficiency and Productivity: AI automates routine tasks, freeing
up human workers to focus on more creative and strategic
endeavors. This increases productivity and reduces the risk of
human error.
</li>
<li>
Improved Decision-Making: AI systems can analyze vast datasets
and provide insights that humans might overlook. This helps
businesses make data-driven decisions and stay competitive.
</li>
<li>
Enhanced Healthcare: AI assists medical professionals in
diagnosing diseases, predicting outbreaks, and developing
personalized treatment plans, ultimately improving patient
outcomes.
</li>
<li>
Safety and Security: AI is used in cybersecurity to detect and
prevent cyberattacks. It also enhances physical security through
facial recognition and surveillance systems.
</li>
</ul>
<h3>Challenges and Concerns</h3>
<p>
Despite its advantages, AI also presents challenges and concerns:
</p>
<ul>
<li>
Job Displacement: One of the most significant concerns
surrounding AI is the potential for job displacement. As AI
systems automate tasks, some traditional jobs may become
obsolete, requiring a shift in workforce skills and retraining.
</li>
<li>
Bias and Fairness: AI algorithms can inherit biases present in
the data they are trained on, leading to discriminatory
outcomes. Ensuring fairness and transparency in AI systems is a
critical challenge.
</li>
<li>
Privacy: AI systems often require access to vast amounts of
personal data. Protecting individuals' privacy while harnessing
the power of AI is an ongoing concern.
</li>
</ul>
</article>
</div>
</div>
</main>
从技术上来说,如果你的页面没有垂直滚动,那么滚动的像素数将始终为0。所以我们可以将标题的
position
设置为static
,当window.scrollY > 0
时将其设置为sticky
再次当 windows.scrollY <= 0
.
也许有人可以向我们解释是否最好保留CSS中已经设置的位置粘性。
// HTML
<header id="header"></header>
// CSS
#header {
background-color: red;
width: 500px;
height: 100px;
position: sticky;
left: 0;
right: 0;
margin: 0 auto;
}
// JavaScript
const header = document.getElementById("header")
window.addEventListener("scroll", function(e) {
if(window.scrollY > 0) {
header.style.position = "static"
} else {
header.style.position = "sticky"
}
})