css-protips

css-protips

精选CSS高级技巧提升开发效率

css-protips项目汇集了多种实用的CSS技巧,涵盖CSS重置、选择器使用、布局技巧等方面。通过学习如何正确设置box-sizing、创建纯CSS滑块、实现垂直居中等技巧,开发者可以编写出更高效、易维护的样式代码,从而提升整体CSS开发水平。

CSS前端开发网页设计样式技巧响应式设计Github开源项目
<div align="center"> <img src="./assets/img/bulb.svg" width="200" alt="light bulb icon"> </div>

CSS Protips Awesome

A collection of tips to help take your CSS skills pro.

For other great lists check out @sindresorhus's curated list of awesome lists.

Table of Contents

Protips

  1. Use a CSS Reset
  2. Inherit box-sizing
  3. Use unset Instead of Resetting All Properties
  4. Use :not() to Apply/Unapply Borders on Navigation
  5. Check if Font Is Installed Locally
  6. Add line-height to body
  7. Set :focus for Form Elements
  8. Vertically-Center Anything
  9. Use aspect-ratio Instead of Height/Width
  10. Comma-Separated Lists
  11. Select Items Using Negative nth-child
  12. Use SVG for Icons
  13. Use the "Lobotomized Owl" Selector
  14. Use max-height for Pure CSS Sliders
  15. Equal-Width Table Cells
  16. Get Rid of Margin Hacks With Flexbox
  17. Use Attribute Selectors with Empty Links
  18. Control Specificity Better With :is()
  19. Style "Default" Links
  20. Intrinsic Ratio Boxes
  21. Style Broken Images
  22. Use rem for Global Sizing; Use em for Local Sizing
  23. Hide Autoplay Videos That Aren't Muted
  24. Use :root for Flexible Type
  25. Set font-size on Form Elements for a Better Mobile Experience
  26. Use Pointer Events to Control Mouse Events
  27. Set display: none on Line Breaks Used as Spacing
  28. Use :empty to Hide Empty HTML Elements

Use a CSS Reset

CSS resets help enforce style consistency across different browsers with a clean slate for styling elements. There are plenty of reset patterns to find, or you can use a more simplified reset approach:

*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

Now elements will be stripped of margins and padding, and box-sizing lets you manage layouts with the CSS box model.

Demo

[!TIP] If you follow the Inherit box-sizing tip below you might opt to not include the box-sizing property in your CSS reset.

<sup>back to table of contents</sup>

Inherit box-sizing

Let box-sizing be inherited from html:

html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; }

This makes it easier to change box-sizing in plugins or other components that leverage other behavior.

Demo

<sup>back to table of contents</sup>

Use unset Instead of Resetting All Properties

When resetting an element's properties, it's not necessary to reset each individual property:

button { background: none; border: none; color: inherit; font: inherit; outline: none; padding: 0; }

You can specify all of an element's properties using the all shorthand. Setting the value to unset changes an element's properties to their initial values:

button { all: unset; }

<sup>back to table of contents</sup>

Use :not() to Apply/Unapply Borders on Navigation

Instead of putting on the border...

/* add border */ .nav li { border-right: 1px solid #666; }

...and then taking it off the last element...

/* remove border */ .nav li:last-child { border-right: none; }

...use the :not() pseudo-class to only apply to the elements you want:

.nav li:not(:last-child) { border-right: 1px solid #666; }

Here, the CSS selector is read as a human would describe it.

Demo

<sup>back to table of contents</sup>

Check if Font Is Installed Locally

You can check if a font is installed locally before fetching it remotely, which is a good performance tip, too.

@font-face { font-family: "Dank Mono"; src: /* Full name */ local("Dank Mono"), /* Postscript name */ local("Dank Mono"), /* Otherwise, download it! */ url("//...a.server/fonts/DankMono.woff"); } code { font-family: "Dank Mono", system-ui-monospace; }

H/T to Adam Argyle for sharing this protip and demo.

<sup>back to table of contents</sup>

Add line-height to body

You don't need to add line-height to each <p>, <h*>, et al. separately. Instead, add it to body:

body { line-height: 1.5; }

This way textual elements can inherit from body easily.

Demo

<sup>back to table of contents</sup>

Set :focus for Form Elements

Sighted keyboard users rely on focus to determine where keyboard events go in the page. Make focus for form elements stand out and consistent than a browser's default implementation:

a:focus, button:focus, input:focus, select:focus, textarea:focus { box-shadow: none; outline: #000 dotted 2px; outline-offset: .05em; }

Demo

<sup>back to table of contents</sup>

Vertically-Center Anything

No, it's not black magic, you really can center elements vertically. You can do this with flexbox...

html, body { height: 100%; } body { align-items: center; display: flex; justify-content: center; }

...and also with CSS Grid:

body { display: grid; height: 100vh; place-items: center; }

[!TIP] Want to center something else? Vertically, horizontally...anything, anytime, anywhere? CSS-Tricks has a nice write-up on doing all of that.

Demo

<sup>back to table of contents</sup>

Use aspect-ratio Instead of Height/Width

The aspect-ratio property allows you to easily size elements and maintain consistent width-to-height ratio. This is incredibly useful in responsive web design to prevent layout shift. Use object-fit with it to prevent disrupting the layout if the height/width values of images changes.

img { aspect-ratio: 16 / 9; /* width / height */ object-fit: cover; }

Learn more about the aspect-ratio property in this web.dev post.

Demo

<sup>back to table of contents</sup>

Comma-Separated Lists

Make list items look like a real, comma-separated list:

ul > li:not(:last-child)::after { content: ","; }

Use the :not() pseudo-class and no comma will be added to the last item.

[!NOTE] This tip may not be ideal for accessibility, specifically screen readers. And copy/paste from the browser doesn't work with CSS-generated content. Proceed with caution.

<sup>back to table of contents</sup>

Select Items Using Negative nth-child

Use negative nth-child in CSS to select items 1 through n.

li { display: none; } /* select items 1 through 3 and display them */ li:nth-child(-n+3) { display: block; }

Or, since you've already learned a little about using :not(), try:

/* select all items except the first 3 and display them */ li:not(:nth-child(-n+3)) { display: block; }

Demo

<sup>back to table of contents</sup>

Use SVG for Icons

There's no reason not to use SVG for icons:

.logo { background: url("logo.svg"); }

SVG scales well for all resolution types and is supported in all browsers back to IE9. Ditch your .png, .jpg, or .gif-jif-whatev files.

[!NOTE] If you have SVG icon-only buttons for sighted users and the SVG fails to load, this will help maintain accessibility:

.no-svg .icon-only::after { content: attr(aria-label); }

<sup>back to table of contents</sup>

Use the "Lobotomized Owl" Selector

It may have a strange name but using the universal selector (*) with the adjacent sibling selector (+) can provide a powerful CSS capability:

* + * { margin-top: 1.5em; }

In this example, all elements in the flow of the document that follow other elements will receive margin-top: 1.5em.

[!TIP] For more on the "lobotomized owl" selector, read Heydon Pickering's post on A List Apart.

Demo

<sup>back to table of contents</sup>

Use max-height for Pure CSS Sliders

Implement CSS-only sliders using max-height with overflow hidden:

.slider { max-height: 200px; overflow-y: hidden; width: 300px; } .slider:hover { max-height: 600px; overflow-y: scroll; }

The element expands to the max-height value on hover and the slider displays as a result of the overflow.

<sup>back to table of contents</sup>

Equal-Width Table Cells

Tables can be a pain to work with. Try using table-layout: fixed to keep cells at equal width:

.calendar { table-layout: fixed; }

Pain-free table layouts.

Demo

<sup>back to table of contents</sup>

Get Rid of Margin Hacks With Flexbox

When working with column gutters you can get rid of nth-, first-, and last-child hacks by using flexbox's space-between property:

.list { display: flex; justify-content: space-between; } .list .person { flex-basis: 23%; }

Now column gutters always appear evenly-spaced.

<sup>back to table of contents</sup>

Use Attribute Selectors with Empty Links

Display links when the <a> element has no text value but the href attribute has a link:

a[href^="http"]:empty::before { content: attr(href); }

That's really convenient.

Demo

[!NOTE] This tip may not be ideal for accessibility, specifically screen readers. And copy/paste from the browser doesn't work with CSS-generated content. Proceed with caution.

<sup>back to table of contents</sup>

Control Specificity Better with :is()

The :is() pseudo-class is used to target multiple selectors at once, reducing redundancy and enhancing code readability. This is incredibly useful for writing large selectors in a more compact form.

:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) { color: green; }

The above ruleset is equivalent to the following number selector rules...

section h1, section h2, section h3, section h4, section h5, section h6, article h1, article h2, article h3, article h4, article h5, article h6, aside h1, aside h2, aside h3, aside h4, aside h5, aside h6, nav h1, nav h2, nav h3, nav h4, nav h5, nav h6 { color: green; }

Demo

<sup>back to table of contents</sup>

Style "Default" Links

Add a style for "default" links:

a[href]:not([class]) { color: #008000; text-decoration: underline; }

Now links that are inserted via a CMS, which don't usually have a class attribute, will have a distinction without generically affecting the cascade.

<sup>back to table of contents</sup>

Intrinsic Ratio Boxes

To create a box with an intrinsic ratio, all you need to do is apply top or bottom padding to a div:

.container { height: 0; padding-bottom: 20%; position: relative; } .container div { border: 2px dashed #ddd; height: 100%; left: 0; position: absolute; top: 0; width: 100%; }

Using 20% for padding makes the height of the box equal to 20% of its width. No matter the width of the viewport, the child div will keep its aspect ratio (100% / 20% = 5:1).

Demo

<sup>back to table of contents</sup>

Style Broken Images

Make broken images more aesthetically-pleasing with a little bit of CSS:

img { display: block; font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; position: relative; text-align: center; width: 100%; }

Now add pseudo-elements rules to display a user message and URL reference of the broken image:

img::before { content: "We're sorry, the image below is broken :("; display: block; margin-bottom: 10px; } img::after { content: "(url: " attr(src) ")"; display: block; font-size: 12px; }

[!TIP] Learn more about styling for this pattern in Ire Aderinokun's post.

<sup>back to table of contents</sup>

Use rem for Global Sizing; Use em for Local Sizing

After setting the base font size

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

下拉加载更多