coffeecop coffeecop - 1 month ago 7
HTML Question

Refer to List item

Is there a way to refer to a ordered list's item number purely in HTML/CSS, so that it updates when the items number updates.

ie. Have the number

4
in the first paragraph below auto update to the number of
Log into your account
, given the list below is an HTML Ordered List (
<ol>
)

If you already have a user account skip to step 4
1. Create user Account
2. Enter you personal information
3. Click 'Create account'
4. Log into your account
5. Do account things...


Becomes the following, without having to manually update the first paragraph

If you already have a user account skip to step 5
1. Create user Account
2. Select your account type
3. Enter you personal information
4. Click 'Create account'
5. Log into your account
6. Do account things...

Answer

You can do it with just CSS, but it takes a hacky solution, with surprisingly good browser support.

Basically, the idea is to use CSS counters to count the number of items to the list item you want(marked with a class):

<div class="numbered-stuff">
  <p>
    If you want the important stuff, skip to step
  </p>
  <ol>
    <li>Stuff</li>
    <li>Stuff</li>
    <li>Stuff</li>
    <li>Stuff</li>
    <li class="important">Important Stuff</li>
    <li>Stuff</li>
  </ol>
</div>

In this case, we have the 5th item marked with our class, so we need to increment the counter for every item before it:

ol {
  counter-reset: stuff;
}

ol li {
  counter-increment: stuff;
}

ol li.important:after{
  content:counter(stuff);
}

Quiet simple, right? Now we just need to position the after element beside the text. Putting it all together(With a little bit of style, because ugly UI's suck):

@import url('https://fonts.googleapis.com/css?family=Lato');
 body,
html {
  margin: 0;
  background: #efefef;
}
.numbered-stuff {
  position: relative;
  display: inline-block;
  padding-right: 25px;
  font-family: 'Lato', sans-serif;
}
p {
  background: white;
  margin: 0;
  padding: 10px;
}
ol {
  counter-reset: stuff;
}
ol li {
  counter-increment: stuff;
}
ol li.important:after {
  content: counter(stuff);
  position: absolute;
  top: 0;
  right: 0;
  padding: 10px;
  color: white;
  background: #009688;
}
}
<div class="numbered-stuff">
  <p>
    If you want the important stuff, skip to step
  </p>
  <ol>
    <li>Stuff</li>
    <li>Stuff</li>
    <li>Stuff</li>
    <li>Stuff</li>
    <li class="important">Important Stuff</li>
    <li>Stuff</li>
  </ol>
</div>

Of course, you can change the html how you want, but the concept stays the same

Comments