Why do developers often use multiple divs with single classes instead of a single div with multiple classes

lightning-web-components

Why do developers often use multiple divs with single classes instead of a single div with multiple classes?

For example this:

<div class="slds-form-element slds-size--1-of-2">
<div class="slds-grid slds-gutters slds-wrap slds-size_1-of-1 slds-p-horizontal_small slds-p-vertical_small">
<div class="slds-col slds-wrap slds-small-size_1-of-1 slds-medium-size_1-of-1 slds-large-size_1-of-1">
<legend class="slds-form-element__legend slds-form-element__label">Account Lookup</legend>
<lightning-combobox name="Accounts" label="Accounts" value={valueAccounts} placeholder="Select an Account" options={accounts} onchange={storeAccount} variant="label-hidden"></lightning-combobox>
</div>
</div>
</div>

Instead of this?

<div class="slds-form-element slds-size--1-of-2 slds-grid slds-gutters slds-wrap slds-size_1-of-1 slds-p-horizontal_small slds-p-vertical_small slds-col slds-wrap slds-small-size_1-of-1 slds-medium-size_1-of-1 slds-large-size_1-of-1">
<legend class="slds-form-element__legend slds-form-element__label">Account Lookup</legend>
<lightning-combobox name="Accounts" label="Accounts" value={valueAccounts} placeholder="Select an Account" options={accounts} onchange={storeAccount} variant="label-hidden"></lightning-combobox>
</div>

Is it a best practice? Or is it functional (there are really supposed to be nested divs as it impacts the UI)?

Best Answer

Many of the sizing CSS classes (slds-size) in this example aren't compatible with each other, and things like slds-grid and slds-col do different things, and slds-col and slds-size classes typically wouldn't be used together, either. In summary, the developer here is generally "correct" that there should be multiple div elements. Except, that's not what a lookup is supposed to look like. They created a faux lookup element that doesn't look like a real lookup field. In Salesforce, lightning-combobox doesn't allow typing to filter, and so this lookup field would be a terrible experience. The solution here wouldn't be to smash the classes together into a single div, but rather rewrite the component entirely to use a reusable lookup, or copy-paste from an open-source project that implements proper lookups.

Related Topic