The GitHub Blog 04月19日 03:38
How to make your images in Markdown on GitHub adjust for dark mode and light mode
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍如何在GitHub的Markdown文件中,使用HTML的``元素,使图片能够根据用户选择的深色或浅色模式自动切换。这使得README文件中的图片能够更好地融入GitHub的界面风格,避免在不同主题下出现突兀的视觉效果。通过简单的代码片段,开发者可以为深色和浅色模式分别指定不同的图片,提升项目的整体美观度和用户体验。

💡 使用``元素实现图片主题自适应:通过在Markdown中使用``标签,开发者可以定义多个图像源,针对不同的颜色模式加载不同的图片。

🎨 针对深色模式的图片展示:当用户启用GitHub的深色模式时,浏览器会加载``中指定的`srcset`图片,确保图片与深色背景协调。

🔆 针对浅色模式的图片展示:同样地,当用户使用浅色模式时,``中的图片将被加载,以匹配浅色主题。

🖼️ 备用图片:如果浏览器不支持``元素,或者用户的系统颜色模式与定义的媒体查询不匹配,`...`标签中的备用图片将被显示,确保在任何情况下都有图片呈现。

🚀 应用范围:这种技术不仅适用于README文件,还可以应用于GitHub上托管的文档和其他Markdown文件,提升整个项目在GitHub上的视觉表现。

GitHub supports dark mode and light mode, and as developers, we can make our README images look great in both themes. Here’s a quick guide to using the <picture> element in your GitHub Markdown files to dynamically switch images based on the user’s color scheme.

When developers switch to GitHub’s dark mode (or vice versa), standard images can look out of place, with bright backgrounds or clashing colors.

Instead of forcing a one-size-fits-all image, you can tailor your visuals to blend seamlessly with the theme. It’s a small change, but it can make your project look much more polished.

One snippet, two themes!

Here’s the magic snippet you can copy into your README (or any Markdown file):

<picture>  <source media="(prefers-color-scheme: dark)" srcset="dark-mode-image.png">  <source media="(prefers-color-scheme: light)" srcset="light-mode-image.png">  <img alt="Fallback image description" src="default-image.png"></picture>

Now, we say it’s magic, but let’s take a peek behind the curtain to show how it works:

You can use this approach in your repo README files, documentation hosted on GitHub, and any other Markdown files rendered on GitHub.com!

Demo

What’s better than a demo to help you get started? Here’s what this looks like in practice:

The post How to make your images in Markdown on GitHub adjust for dark mode and light mode appeared first on The GitHub Blog.

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

GitHub Markdown 深色模式 浅色模式 图片自适应
相关文章