Search code examples
htmlcsshtml-listscss-content

Handling paragraphs inside list items with a custom CSS content


This is how a paragraph looks like inside a non-styled list item (<li>):

enter image description here

<li>
  <p>
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
  </p>
</li>

However, when using a custom list style type it looks like this:

enter image description here

The HTML for this is:

<li class="docs-test">
  <p>
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
    hehehe
  </p>
</li>

The CSS is:

.docs-test {
  color: red;
  list-style-type: none;
}

.docs-test::before {
  content: '\2022 ';
  color: #828282;
  display: inline-block;
  margin-right: 10px;
}

.docs-test p {
  display: inline-block;
}

I know that for this particular custom list style type I could use list-style-image. However, I have other customs list style types for the which I cannot use list-style-image.

How can I make it so that paragraphs inside list items with a custom CSS content list style type don't jump to the beginning of the next "line"? The goal is for these custom list style lists to handle paragraphs the same way regular lists without styling do.

http://jsbin.com/kimilaniga/1/edit?html,css,output


Solution

  • Here is one way of realizing the styling that you want.

    Use absolute positioning to place the generated content from the ::before pseudo-element to the left of the left edge of the <li> block element.

    First, you need to add position: relative to the .docs-test CSS rule to allow the pseudo-element to be positioned with respect to the li parent block.

    Second, add position: absolute and appropriate top and left offset values to get the styling that you want.

    You also need to reset the margins on the p element to zero.

    .docs-test {
      color: red;
      list-style-type: none;
      display: inline-block;
      position: relative;
    }
    
    .docs-test::before {
      content: '\2022 ';
      color: #828282;
      display: block;
      text-align: center;
      position: absolute;
      outline: 1px dotted gray; /* for demo only */
      width: 20px;
      left: -20px;
      top: 0;
    }
    
    .docs-test p {
      display: inline-block;
      margin: 0;
    }
    <ul>
      <li>
        <p>
          hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe
        </p>
      </li>
    
      <li class="docs-test">
        <p>
          hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe hehehe
          </p>
      </li>
    </ul>