April 12, 2012

In CSS, When I scroll the scroll bar, the background-color of <li> disappeared

Question by UniMouS

HTML code like this:

<div>
    <ol>
        <li class='a'>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</li>
        <li class='b'>bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb</li>
    </ol>
</div>

CSS code like this:

div {
    width: 400px;
    overflow-x: scroll
}

.a {
    background-color: red;
}

.b {
    background-color: blue;
}

When I scroll the scroll bar, I see that the background color is only applied to the original unscrolled region. How can I solve this problem.

My Code is Here


EDIT

Another example showing my problem clearly.

I have a second problem now: the second line disappeared…why

Answer by James Johnson

For the list items you need to set the display property to inline-block and set the min-width property to 100%. Here’s your jsFiddle, and see below:

div {
    width: 400px;
    overflow-x: scroll;   
}

li {
    min-width: 100%;
    white-space: nowrap;
    display: table-row; /* or inline-block */   
}

.a, .c, .e, .g {
    background-color: red;
}

.b, .d, .f {
    background-color: blue;
}​

EDIT

To make all of the li elements the width of the longest li, use display: table-row.

See this jsFiddle for a demonstration.

li {
    min-width: 100%;
    white-space: nowrap;
    display: table-row;    
}

Answer by Starx

You can overcome this problem by defining your lists as inline

li { display: inline; }

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!