开发者

How to force horizontal scrolling depending on size of contents

I want to have a horizontal scrollbar if necessary, by having the 'child' divs be added side-by-size instead of getting pushed to the next row when the parent isn't wide enough.

My code is below. If you set .mid to have width: 1000px you'll see what I'm going for, only I only want it to be as wide as the dynamically generated children.

<html>
<head>

    <style type="text/css">

        .parent {
            width: 400px;
            back开发者_如何学Goground-color: #666;
            overflow:scroll;  /* cater to the older browsers */
            overflow-y:hidden; /* Hide vertical*/
        }

        .mid {
            background-color: red;
        }

        .child {
            display:inline-block;
            background-color: #ccc;
            border: 1px solid black;
            width: 190px;
        }

    </style>

</head>
<body>
    <div class="parent">
        <div class="mid">
            <div class="child">
                I am a child.
            </div>
            <div class="child">
                I am a child.
            </div>
            <div class="child">
                I am a child.
            </div>  
        </div>
    </div>

</body>
</html>


Heck, might as well answer this. You're going to need Javascript for this, but given that you already use that to dynamically generate the child elements, it shouldn't really be a problem.

Assuming you're using jQuery, add these two lines after you generate the element:

var child = $('child');
$('.mid').width(child.length * child.outerWidth(true));

Sorry about the miscommunication

Using this, however, will create another problem. When you use display: inline-block, a whitespace added behind each div, so jQuery cannot get the correct width. This wouldn't happen if you use float: left instead though.


People have been here before and found the best / easiest way to do this. Look here:

http://css-tricks.com/how-to-create-a-horizontally-scrolling-site/


You could try and use overflow:auto

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜