Search code examples
htmlcssthreaded-comments

Need advice on html/css structure for indented, threaded comments


I want to have a comments section in my app that looks like this:

response1
 response1a
 response1b
  response1b1
response2
 response2a
 response2b
 response2c
  response2c1
   response2c1a
    response2c1a1
     response2c1a1
      response2c1a1a
       response2c1a1a1

I believe it's called threaded comments. You've probably seen this format on many online discussion sites such as reddit.

What I'm wondering is how to implement this in the HTML of my app?

What type of html/css combination would make the most sense to allow this type of application-determined indenting?


Solution

  • In your HTML:

    <div class="comment">
      Response1
      <div class="comment">
        Response1a
        <div class="comment">
          Response1a1
        </div>
      </div>
      <div class="comment">
        Response1b
      </div>
    </div>
    

    And in your CSS:

    .comment { margin-left: 50px; }
    

    This approach is very flexible and portable. You could also use <ul>/<li> instead of <div> (I guess it's possible to argue both in favour and against seeing threaded comments as semantically equivalent to unordered lists). The inner comment can also be wrapped in another <div> if you require it for additionaly CSS styling.


    Update: I (slightly) prefer <div>s over <ul>/<li> because it simplifies your implementation.

    Firstly, if you go with the list-based approach, you have to strip the default <li> style that most browsers use (a bullet point and padding). Secondly, you will probably also want to target the set of <ul>/<li>s that are specific to your threaded comments, because they should look different from other list structures. This means that even with the "semantic" approach, you have resort to classes. So in the end, what advantage do you really get, and is it worth the extra hassle?

    We've been a little more careful with applying <ul> structures like this in our projects, and so far we're really happy about it. And apparently we're not the only one.