Matoeil
Matoeil

Reputation: 7289

CSS float and responsive behaviour

Here is my template:

<div id="block1">text</div>
<div id="block2">
   <span>content of variable size</span>   
</div>

and some basic CSS

#block1 {
    float:left;
}

#block2 {
    float:right;
}

#block2 span {     
}

When reducing the width, how could I make it behave so that, once the two divs cannot fit the page inline, the second div will go below the first (rather than be right floated anymore)?

NOTE: I would like to avoid using media queries.

This responsive theme CSS would be used for multiple sites with content of different sizes.

JSFiddle

In this current JSFiddle, The second div is on the right hand-side. It is fine to me.

If possible without media queries, i would like to design css so that once the second div goes below , the span content is not at the right-hand side

Upvotes: 0

Views: 851

Answers (3)

Alexander Solonik
Alexander Solonik

Reputation: 10230

Too many media queries would not make for a pretty responsive design, not to mention they would be a headache.

Anyway, you would have to use at least one media query to achieve a truly responsive design, the simplest example is below:

<div id="block1">text</div>
<div id="block2"> <span>content of variable size</span> 
</div>  


* {
    padding: 0;
    margin: 0;
}
#block1 {
    float:left;
    height: 200px;
    background: yellow;
    width: 49.5%;
    margin-right: .5%;
}
#block2 {
    float:right;
    height: 200px;
    background: tomato;
    width: 49.5%;
    margin-left: .5%;
}
#block2 span {
}
@media only screen and (max-width : 768px) {
    #block1 {
        float:none;
        width: 100%;
    }
    #block2 {
        float:none;
        width: 100%;
    }
}

Fiddle here.

If you want to have a look at something more practical, a good starting point is here(its an example of an accordion changing layouts depending on screen size, using media queries).

Upvotes: 1

Rob
Rob

Reputation: 15160

You can set min-width on the divs. Then, when the line is too small, the one on the right will drop down. However, it will still be floated which may cause issues. That's where media queries come into play to fix such things.

Upvotes: 1

Sebastien
Sebastien

Reputation: 1102

If you mean "I want div2 to go below, but aligned left this time", it's not possible as this behaviour is not predictable using CSS only.

There's no CSS-way to know when it goes below, so impossible to change the floating attribute at this moment.

You could achieve this using Javascript or jQuery. Logic would be:

on ( window resize ) {
    if ( div1_width + div2_width > container_width ) {
        Change div2 CSS.
    }
}

Of course I would suggest to use media queries too.

Upvotes: 2

Related Questions