1

How can target multiple elements under the same div without having to repeat the div's name? I know I am able to select multiple elements of a parent div using the following CSS code,

.container h3,
.container p {
  text-align: left;
}

But, is there any other short-hand way to target the h3 and p tags under the .container div?

David Thomas
  • 249,100
  • 51
  • 377
  • 410
allgeo
  • 21
  • 3
  • 1
    A *decedent* is a person who is dead while I'm going to correct the typo immediately, I just thought I'd leave the information for you. – David Thomas Apr 14 '22 at 18:53

2 Answers2

3

I'd suggest using the – relatively new – :is() syntax:

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

.container {
  border: 0.3em solid rebeccapurple;
  margin-block: 1em;
  margin-inline: auto;
  width: clamp(30em, 50vw, 600px);
}

.container :is(h3, p) {
  border: 1px solid #000;
  color: rebeccapurple;
  margin-block: 1em;
  margin-inline: auto;
  padding-inline: 1em;
  width: 80%;
}
<h3>A &lt;h3&gt; element, that should probably be a &lt;h2&gt;</h3>
<div class="container">
  <h3>A properly-used, and selected, &lt;h3&gt; element</h3>
  <p>...and an adjacent &lt;p&gt; element.</p>
</div>
<p>Some text in a paragraph that shouldn't be styled.</p>

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
2

In vanilla CSS, what you have is the best way of doing it. If you use a css precompiler such as SASS, you can instead nest objects so that your code could look like this:

.container {
  h3, p {
    text-align: left;
  }
}
Robin
  • 262
  • 2
  • 10