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

通用选择器与body选择器的使用疑问:box-sizing等全局样式应声明于哪个选择器?

Should I put box-sizing: border-box;, padding: 0;, margin: 0; in the universal selector (*) or the body selector?

Hey there! This is such a common question when you're setting up base styles for a project—let's break down the difference and which approach makes sense for your needs.

What each selector does

Universal selector (*)

The * selector targets every single element in your HTML document—this includes <html>, <body>, <p>, <div>, <ul>, form inputs, buttons, even pseudo-elements like ::before and ::after (though you’ll need to target those separately if you want to inherit styles).

If you apply your styles here:

  • box-sizing: border-box will ensure every element’s total width/height includes padding and borders (no more unexpected layout shifts from the default content-box sizing)
  • padding: 0 and margin: 0 will strip away the default browser margins/padding from all elements (so no random space around paragraphs, lists, headers, etc.)

A robust pattern for box-sizing often includes pseudo-elements via inheritance:

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

*::before,
*::after {
  box-sizing: inherit; /* Ensures pseudo-elements follow the same box model */
}

body selector

The body selector only targets the <body> tag itself. Applying your styles here would:

  • Only reset the margin/padding of the <body> element (you’ll still get default spacing on <p>, <ul>, <h1>, etc.)
  • Only apply border-box to the <body>—all other elements will still use the default content-box sizing, leading to inconsistent layout calculations.

Which should you use?

For your specific goal of setting these styles globally, the universal selector is the right choice. It ensures consistent styling across every element in your project, eliminating browser defaults that can throw off your layout.

A quick note: Some developers avoid using * for margin/padding reset if they want to preserve default styles for form elements (like inputs or buttons), but if you’re building a project where you want full control over all spacing, the universal reset works great. Alternatively, you can target specific elements for reset instead, but that’s more verbose.

内容的提问来源于stack exchange,提问作者pratik thapa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 11:52:45