James R
James R

Reputation: 151

CSS floated div, not shrinking to content

This is very odd to me, and although I've searched, everyone seems to have the opposite problem to me (a floated div shrinking)!

I have this page: http://www.tameside.gov.uk/test/news, which uses PHP to generate the divs at the top for various news stories, and it works fine. However the items (which are floated divs) are in a div which is floated left, which for some reason isn't shrinking to those items (which are it's only contents).

As far as I was aware, a floated div always shrunk to it's contents, but this particular one is expanding to 100% of the page it seems. I've coloured the background of the containing div in grey to show you what I mean.

I want it to shrink to the contents so that I could use a centering trick, and it would then center the div no matter how many divs are in the top news items. But because it's not shrinking, the trick obviously isn't working.

The CSS for each of the news item divs is below:

.news-top-item {
    border-radius: 10px;
    border-color: #3f7dae;
    border-style: solid;
    border-width: 2px;
    float: left;
    width: 19%;
    text-align: center;
    margin-right: 0.5%;
    height: 13em;
    padding-top: 0.5em;
    cursor: pointer;
    position: relative;
}

They've also got a span inside that has a little CSS attached to it to make the whole thing a link:

.news-top-item span {
    display: inline;
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    left: 0;
    z-index: 2;
    background-image: url('/tmbc_images/include/1pixel.gif');
    cursor: pointer;
}

I doubt that's interfering, but have put it in just in case.

The outer div has only 'float: left' and the background colour applied to it.

Any help would be much appreciated.

Thanks,

James

Upvotes: 3

Views: 3342

Answers (3)

Julien Meilleur
Julien Meilleur

Reputation: 303

You shall remove float:left and use display:inline-block instead

.news-top-item {
    border-radius: 10px;
    border-color: #3f7dae;
    border-style: solid;
    border-width: 2px;
    display:inline-block;
    width: 19%;
    text-align: center;
    margin-right: 0.5%;
    height: 13em;
    padding-top: 0.5em;
    cursor: pointer;
    position: relative;
}

And add text-align:center in your containing div

Upvotes: 1

Eliran Malka
Eliran Malka

Reputation: 16263

use absolute units instead of percentages to define measurements for the inner elements:

.news-top-item {
    border-radius: 10px;
    border-color: #3f7dae;
    border-style: solid;
    border-width: 2px;
    float: left;
    width: 200px; /* <--- */
    text-align: center;
    margin-right: 2px; /* <--- */
    height: 13em;
    padding-top: 0.5em;
    cursor: pointer;
    position: relative;
}

Upvotes: 0

Denny Mueller
Denny Mueller

Reputation: 3615

width:100%;
height:100%;

is 100% of windows size ... Try

width:auto;
height:auto;

Upvotes: 0

Related Questions