You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅通过HTML结合CSS媒体查询修改<h1>标签内容(无需JavaScript)

Swap H1 Text with CSS Media Queries (No JavaScript)

Great question! You can absolutely swap the text inside an <h1> using just HTML and CSS media queries—no JavaScript needed. Here are two reliable approaches to achieve this:

Approach 1: Use CSS Pseudo-Elements

This method keeps your HTML clean by hiding the original text and using a pseudo-element to display (and swap) the content.

HTML & CSS Code

<html>
<head>
<title>Media Query Text Swap</title>
<style>
h1 {
  /* Hide the original off-screen (preserves basic accessibility) */
  text-indent: -9999px;
  position: relative;
}

/* Default state: Show original text via pseudo-element */
h1::before {
  content: "Hello from this side";
  position: absolute;
  left: 9999px;
  text-indent: 0;
}

/* Media Query: Swap text when screen is <= 768px wide */
@media (max-width: 768px) {
  h1::before {
    content: "Hello from the other side!";
  }
}
</style>
</head>
<body>
<h1>Hello from this side</h1>
</body>
</html>

Notes

  • The original text is moved off-screen instead of deleted, which helps maintain basic accessibility for screen readers.
  • Most modern assistive tools will read the pseudo-element content, but test with older screen readers if accessibility is a critical requirement.

Approach 2: Use Toggleable Inline Elements

This approach uses separate <span> elements for each text version, then toggles their visibility with media queries. It’s more semantic and ideal for accessibility-focused projects.

HTML & CSS Code

<html>
<head>
<title>Media Query Text Swap</title>
<style>
/* Default state: Show original text, hide replacement */
.h1-original {
  display: inline;
}
.h1-replacement {
  display: none;
}

/* Media Query: Swap visibility when screen is <= 768px wide */
@media (max-width: 768px) {
  .h1-original {
    display: none;
  }
  .h1-replacement {
    display: inline;
  }
}
</style>
</head>
<body>
<h1>
  <span class="h1-original">Hello from this side</span>
  <span class="h1-replacement">Hello from the other side!</span>
</h1>
</body>
</html>

Notes

  • All text content lives directly in the HTML, making it fully accessible to screen readers and other assistive technologies.
  • It’s easier to modify or add additional text variants if needed later.

内容的提问来源于stack exchange,提问作者Bhavik Sejpal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:10:35