简体   繁体   中英

HTML expand div horizontally to fit children

I'm creating a horizontally scrolling web site. There's a container div which I want to retain a fixed height but expand as required horizontally to fit the content inside it. At the moment the div only expands horizontally as far as the page width. There are actually 9 images to display but only the first 4 are shown. See code and image below. How do I make the container div expand horizontally to show all images please?

在此处输入图片说明

css:

body
{
    background-color:#dbdbdb; 
}

div.infinite-container
{
    background-color:#db0080; 
    height:180px;
}

img.infinite-item
{
width="320"; 
height="180";
margin-right:8px;
margin-bottom:8px;
display:inline-block;
}

.infinite-more-link 
{
visibility:hidden;
}

PHP:

<div class="infinite-container">');


if ($num_results > 0)
{
    $array = array();
    while ($row = mysql_fetch_assoc($result))
    {
        $array[] = $row;
    }

    for ($i = 0; $i < $numImagesPerPage; $i++)
    {   
        $filePath = "animations/".$array[$i]['animationid'].".gif";
        echo('<img class="infinite-item" src="'.$filePath.'"/>');
    }
}    

echo('</div>');

This screenshot is after the changes below suggested by Andrei. The pink area is the container div. The images appear to break out below it.

在此处输入图片说明

From the code you posted, doing something like this should work:

body
{
    background-color:#dbdbdb;
    overflow:auto;
}
div.infinite-container
{
    background-color:#db0080; 
    height:180px;
    display:inline-block;
    white-space: nowrap;
}

img.infinite-item
{
    width: 320px; 
    height: 180px;
    margin-right:8px;
    margin-bottom:8px;
    display:inline-block;
}

jsFiddle example:

http://jsfiddle.net/S6Abd/

What this does is:

  • set the display mode to inline-block on the container. This way the container will be as large as needed to contain all items.
  • set overflow:auto on body to show scroll-bars.
  • correct the width and height of each item.
  • add white-space: nowrap; to the container to force the items to stay on one line.

Add this CSS style :)

div.infinite-container
{
    width:2952px; /* (320 + 8) * 9 = 2952 */
}

But on the serious note - DIV shows (kind of) all your images, only images 5-9 are in next line and because container have fixed height, then they are hidden.

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