CSS: селектор первого типа применяется ко всем (с использованием тега html, а не класса)

Селектор :first-of-type применяется ко всем моим тегам p, я читал в Интернете, что вы можете использовать его только для элементов HTML, а не для классов, поэтому я использую его для тега p, и он по-прежнему применяется ко всем тегам p. В чем проблема ?

.doing p {
    font-size: calc(0.5vw + 12px);
    color: #2A2A2C;
    font-weight: 300;
}

.doing p:first-of-type {
    padding-top: 45px;
    padding-bottom: 7%;
    width: 70%;
}
<section class = "doing">
        <h1 class = "doing-title">What we <span>do.<img src = "style/img/linepurple.png" class = "line-purple-do"
                    alt = ""></span></h1>
        <p>Linking advertisers and publishers to their maximum potential.
            Axeite develops desktop and mobile applications. We also offer a smart targeting affiliation system that is
            fraudproof. With a thorough tracking capability, the Axeite affiliation system is transparent and offers
            insightful reports for your business.
        </p>

        <div class = "doing-boxes">
            <div class = "box">
                <div class = "circle"></div>
                <p>Axeite connects advertisers and publishers globally. With fast integration on high-performing
                    products for web, mobile (iOS and Android), and video, that’s a win-win.
                </p>
            </div>
            <div class = "box">
                <div class = "circle"></div>
                <p>Monetize with our creative and authentic solutions while engaging every user throughout the marketing
                    funnel
                </p>
            </div>
            <div class = "box">
                <div class = "circle"></div>
                <p>Our all-round monetization packages are fit for all business demands in any industry. With them, you
                    maximize your ROI without the stress of expensive trial-and-error methods.
                </p>
            </div>
        </div>
    </section>

Как видно из фрагмента кода, заполнение применяется ко всем тегам p.

"В чем проблема ?" - ваше непонимание "области действия" селектора? developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type: «Псевдокласс CSS :first-of-type представляет первый элемент своего типа среди группы родственных элементов». Ни один из ваших p элементов здесь имеет никаких p братьев и сестер для начала. Это все первый элемент своего типа в соответствующем родительском элементе.
CBroe 22.03.2022 14:52

Надеюсь найти более глубокую / каноническую цель для обмана, но пока этого достаточно.

TylerH 22.03.2022 16:32
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
2
2
40
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

В этой конкретной ситуации вы должны включить прямой дочерний селектор > в селектор CSS правила, в противном случае также будут выбраны элементы p, которые являются внуками (и, таким образом, первыми в своих прямых родительских элементах). Итак, .doing > p:first-of-type это то, что вы ищете здесь:

.doing p {
    font-size: calc(0.5vw + 12px);
    color: #2A2A2C;
    font-weight: 300;
}

.doing > p:first-of-type {
    padding-top: 45px;
    padding-bottom: 7%;
    width: 70%;
    color: green;
}
<section class = "doing">
        <h1 class = "doing-title">What we <span>do.<img src = "style/img/linepurple.png" class = "line-purple-do"
                    alt = ""></span></h1>
        <p>Linking advertisers and publishers to their maximum potential.
            Axeite develops desktop and mobile applications. We also offer a smart targeting affiliation system that is
            fraudproof. With a thorough tracking capability, the Axeite affiliation system is transparent and offers
            insightful reports for your business.
        </p>

        <div class = "doing-boxes">
            <div class = "box">
                <div class = "circle"></div>
                <p>Axeite connects advertisers and publishers globally. With fast integration on high-performing
                    products for web, mobile (iOS and Android), and video, that’s a win-win.
                </p>
            </div>
            <div class = "box">
                <div class = "circle"></div>
                <p>Monetize with our creative and authentic solutions while engaging every user throughout the marketing
                    funnel
                </p>
            </div>
            <div class = "box">
                <div class = "circle"></div>
                <p>Our all-round monetization packages are fit for all business demands in any industry. With them, you
                    maximize your ROI without the stress of expensive trial-and-error methods.
                </p>
            </div>
        </div>
    </section>
Ответ принят как подходящий

У вас есть несколько решений, даже если вы не хотите добавлять к этому класс p:

Решение 1

Вместо этого примените :first-of-type к .doing, и вам нужно использовать >, чтобы применить только к прямым дочерним элементам doing, иначе это будет применяться ко всем p внутри .doing

.doing p {
  font-size: calc(0.5vw + 12px);
  color: #2A2A2C;
  font-weight: 300;
}

.doing:first-of-type > p {
  padding-top: 45px;
  padding-bottom: 7%;
  width: 70%;
  background: red;
}
<section class = "doing">
  <h1 class = "doing-title">What we <span>do.<img src = "style/img/linepurple.png" class = "line-purple-do" alt = ""></span></h1>
  <p>Linking advertisers and publishers to their maximum potential. Axeite develops desktop and mobile applications. We also offer a smart targeting affiliation system that is fraudproof. With a thorough tracking capability, the Axeite affiliation system
    is transparent and offers insightful reports for your business.
  </p>

  <div class = "doing-boxes">
    <div class = "box">
      <div class = "circle"></div>
      <p>Axeite connects advertisers and publishers globally. With fast integration on high-performing products for web, mobile (iOS and Android), and video, that’s a win-win.
      </p>
    </div>
    <div class = "box">
      <div class = "circle"></div>
      <p>Monetize with our creative and authentic solutions while engaging every user throughout the marketing funnel
      </p>
    </div>
    <div class = "box">
      <div class = "circle"></div>
      <p>Our all-round monetization packages are fit for all business demands in any industry. With them, you maximize your ROI without the stress of expensive trial-and-error methods.
      </p>
    </div>
  </div>
</section>

Решение 2

Использование + в .dong-title следующим образом:

.doing p {
  font-size: calc(0.5vw + 12px);
  color: #2A2A2C;
  font-weight: 300;
}

.doing-title + p {
  padding-top: 45px;
  padding-bottom: 7%;
  width: 70%;
  background: red;
}
<section class = "doing">
  <h1 class = "doing-title">What we <span>do.<img src = "style/img/linepurple.png" class = "line-purple-do" alt = ""></span></h1>
  <p>Linking advertisers and publishers to their maximum potential. Axeite develops desktop and mobile applications. We also offer a smart targeting affiliation system that is fraudproof. With a thorough tracking capability, the Axeite affiliation system
    is transparent and offers insightful reports for your business.
  </p>

  <div class = "doing-boxes">
    <div class = "box">
      <div class = "circle"></div>
      <p>Axeite connects advertisers and publishers globally. With fast integration on high-performing products for web, mobile (iOS and Android), and video, that’s a win-win.
      </p>
    </div>
    <div class = "box">
      <div class = "circle"></div>
      <p>Monetize with our creative and authentic solutions while engaging every user throughout the marketing funnel
      </p>
    </div>
    <div class = "box">
      <div class = "circle"></div>
      <p>Our all-round monetization packages are fit for all business demands in any industry. With them, you maximize your ROI without the stress of expensive trial-and-error methods.
      </p>
    </div>
  </div>
</section>

использование + «имя элемента» всегда будет выбирать первое?

Mathi 22.03.2022 14:35

он всегда выбирает ближайшего брата выбранного элемента, в этом случае ближайшим элементом .doing-title является p, см. подробнее о +здесь

dippas 22.03.2022 14:37

Другие вопросы по теме