简体   繁体   中英

<p> tag inside <li> tag with counter based on counter-reset forces unwanted new line

The CSS counter-reset property allows one to automatically number HTML elements (example here ). In addition to the use demonstrated in the link, this property is also useful for making a continuous ordered list on a webpage when the <li> elements do not all occur inside of the same <ol> tag.

However, when there is a <p> tag inside of the <li> tag, this forces the text to appear on a line after the actual counter. Is there any way to prevent this behavior while still using the <p> tag ? That is to say, how can I make the text "Life is bad" in the following minimal working example appear on the same line as its counter while keeping the text inside of the <p> tag in the HTML markup ?

Here's the minimal working example (and on JSFiddle ):

The HTML:

<div id="test">
    <ol>
        <li class="continuous-list">Life is good</li>
        <li class="continuous-list">
            <p>Life is bad</p>
        </li>
    </ol>
    <ol>
        <li class="continuous-list">Life is good</li>
        <li class="continuous-list">Life is good</li>
    </ol>
</div>

The CSS:

#test {
    counter-reset: continuous-counter;
}
li.continuous-list {
    list-style-type: none;
    counter-increment: continuous-counter;
}
li.continuous-list:before {
    content:"(" counter(continuous-counter)") ";
}

Because p is a block level element , you need to make it inline

ol li p {
    display: inline;
}

Demo

Now the above selector will make ALL the p elements inside ol li as display: inline so as you are using an id you can make your selector unique by using

div#test ol li p {
    display: inline; /* Or you can use inline-block as well if you are 
                        looking to work with margins and paddings, inline-block 
                        will be handy */
}

Add float:left to the before

ie

li.continuous-list:before {
    float: left;
    content:"(" counter(continuous-counter)") ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM