通用选择器与body选择器的使用疑问:box-sizing等全局样式应声明于哪个选择器?
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-boxwill ensure every element’s total width/height includes padding and borders (no more unexpected layout shifts from the defaultcontent-boxsizing)padding: 0andmargin: 0will 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-boxto the<body>—all other elements will still use the defaultcontent-boxsizing, 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

