Search code examples
htmlcsscss-floatresponsive-designmedia-queries

Trouble positioning elements using float in a responsive design


I'm working on a responsive website, and I ran into some trouble doing the layout. I broke the problem down to the fewest lines possible.

When the window is larger then 909px I want to place my second content (content2) just below the title. When there is less space availible I want it to be placed below the image.

Currently it always gets placed below the image.

Here's a visual.

I need to find a solution without using absolute positioning, because the title does not have a fixed height. In fact none of my html elements have a fixed height, I do have fixed widths though.

I have been trying to come up with a simple solution for a few hours now. Here's hoping someone can point me in the right direction :)

Thanks for reading!

HTML code:

<div class="wrapper">
  <h1> some title </h1>
  <div class="image"> some img</div>
  <div class="content1"> some content </div>
  <div class="content2"> some other content </div>
</div>

CSS styles:

.content1{
  float: left;
}
.image{
  width: 600px;
}
.content2{
  width: 300px;
  float: right;
}

@screen and (min-width: 768px) and (max-width: 909px){
  .wrapper {
    width: 700px;
  }
  .content1 {
    width: 300px;
  }
}

@screen and (min-width: 909px){
  .wrapper {
    width: 900px;
  }
  .content1{
    width: 600px;
  }
}

Solution

  • Here is one way of doing it for the case of min-width: 909px

    The CSS is:

    @media screen and (min-width: 909px) {
        .wrapper {
            width: 900px;
            outline: 1px dotted blue; /* optional for demo */
        }
        .image {
            width: 600px;
            float: left;
            outline: 1px dotted blue; /* optional for demo */
        }
        .content1 {
            float: left;
            width: 600px;
            outline: 1px dotted blue; /* optional for demo */
        }
        .content2 {
            width: 300px;
            margin-left: 600px;
            outline: 1px dotted blue; /* optional for demo */
        }
    }
    

    and the demo fiddle is: http://jsfiddle.net/audetwebdesign/WfyJL/

    I did not see anything about heights, so I assume that the content will take determine the various heights of the elements.

    How This Works

    In your previous example, content2 is floated so its top edge is placed next to the bottom edge of the nearest, adjacent block level element, which is image.

    To get the desired layout for the 900px format, float image to the left, and keep content2 in the flow but with a 600px left margin to allow the left floated elements to flow down the left hand side of content2.