Search code examples
htmlcsscss-selectorshtml-listslistitem

Can I use CSS to add a bullet point to any element?


Pretty simple question, but I am not sure if it is possible. I want to add an image to act as a bullet in all <h1> elements. I know I can achieve this by:

<span class='bullet'></span><h1>My H1 text here</h1>

with css:

.bullet{
    background: url('bullet.png') no-repeat;
    display:inline-block;
    vertical-align: middle;
    background-size:100%;
    height:25px;
    width:25px;
    margin-right: 5px;
}

but is there an automatic way to do the same thing? I was thinking something like:

h1{
    list-style-image: url('bullet.png');
}

but that only seems to work with <ul> elements. I really don't want to have to paste the <span> element everywhere before the <h1> element. Any ideas?


Solution

  • While you can use a :before pseudo-selector to add a "-" or "•" character in front of your element, it doesn't really make your element behave like a bullet point. Your element may look like a bullet point, but that's just a dirty hack, really, and should be avoided!

    To make your element both (1) look like a bullet point and (2) behave like a bullet point, you should set the display of that element to list-item. Optionally, you can also set list-style-type (default : disc) and list-style-position (default : outside) attributes to modify the behavior / look-and-feel of your list item.

    If your element spans multiple lines, list-style-position should be the default value outside if you want all of your lines to align to the right of your bullet point. In that case, however, it is possible you don't see your actual bullet point, as it would be to the left of the content of your element. If this happens, you can just add a left margin to move the element's content to the right, and your bullet point should show up.


    EXAMPLE 1

    h1 {
        display: list-item; /* This has to be "list-item"                                          */
        margin-left : 1em;  /* If you use default list-style-position 'outside', you may need this */
    }
    <h1>
      Your H1 text should go here. If it consists of multiple
      lines, the left alignment of all lines is the same.
    </h1>
    <h1>
      Here's another item.
    </h1>


    EXAMPLE 2

    h2 {
        display: list-item;          /* This has to be "list-item"                                               */
        list-style-type: square;     /* See https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type     */
        list-style-position: inside; /* See https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-position */
    }
    <h2>
      Your H2 text should go here.
    </h2>
    <h2>
      Note that, if you have multiple lines, only the first 
      line is aligned to the right of the bullet point when
      using list-style-position 'inside'. Subsequent lines
      are left aligned with the left of the bullet point.
    </h2>