2

What i'm trying to do is add a border-radius to the last p of every "block" of p's so before the next h1, I can add the top radius using the + selector but can't figure out how to select the last one of each.

<main>
    <h1>test</h1>
  <p>hello</p>
    <h1>test</h1>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
    <h1>test</h1>
  <p>hello</p>
  <p>hello</p>
    <h1>test</h1>
  <p>hello</p>
  <p>hello</p>
    <h1>test</h1>
  <p>hello</p>
</main>

css

<style>
  p {
    background: black
  }
  h1 + p {
    border-top-left-radius: 1rem;
    border-top-right-radius: 1rem;
  }
</style>

2 Answers2

2

If you are open to deploying a dash of javascript, you can achieve this effect by adding a single line of javascript to the bottom of your page, like this:

<script>
[...document.getElementsByTagName('h2')].forEach((heading) => {if (heading.previousElementSibling) {heading.previousElementSibling.classList.add('last-paragraph')}});
</script>

</body>
</html>

Working Example:

[...document.getElementsByTagName('h2')].forEach((heading) => {if (heading.previousElementSibling) {heading.previousElementSibling.classList.add('last-paragraph')}});
p {
  height: 24px;
  margin: 0 0 -2px 0;
  padding: 6px 12px;
  line-height: 24px;
  border: 2px solid rgb(255, 0, 0);
  border-top: 2px solid rgba(0, 0, 0, 0);
  border-bottom: 2px solid rgba(0, 0, 0, 0);
}

h2 + p {
  border-top: 2px solid rgb(255, 0, 0);
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
}

p.last-paragraph,
p:last-of-type {
  border-bottom: 2px solid rgb(255, 0, 0);
  border-bottom-left-radius: 6px;
  border-bottom-right-radius: 6px;
}
<main>
    <h2>test</h2>
  <p>hello</p>
    <h2>test</h2>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
    <h2>test</h2>
  <p>hello</p>
  <p>hello</p>
    <h2>test</h2>
  <p>hello</p>
  <p>hello</p>
    <h2>test</h2>
  <p>hello</p>
</main>
Rounin
  • 27,134
  • 9
  • 83
  • 108
0

Wrap every block of <p> and use :last-child. If you're doing many <p> it is best to just add a class to each element that has the desired styles.

<div>

  <p>Hello</p>
  <p>Hey</p>

</div>
p:last-child{
  font-size: 30px; // only last element has a font size of 30 px
}

You also didn't close any of your <p> tags. Make sure your code is formatted before posting.

HasanTheSyrian_
  • 140
  • 1
  • 6
  • I understand i could wrap it in a div block using last of type, but i'm trying to reduce markup if possible. Also i would like to be able to expand this to replace the p's with tr's and use it in a table – Nathan Leadill Jul 28 '22 at 19:31
  • I don't see any other way of doing it other than what I mentioned. You can use Javascript, but that's tedious and just bad practice IMO. – HasanTheSyrian_ Jul 28 '22 at 19:45
  • It's better to use JS than to compromise on the HTML. – connexo Jul 28 '22 at 23:24