Dinobot
Dinobot

Reputation: 3

HTML layout - display: inline-block instead of float not working

Sry for the bad title, I couldn't come up with something more descriptive...

I have four types of content, each one in a separate div like this:

<div id="item1">
  some content
</div>
<div id="item2">
  some content
</div>
<div id="item3">
  some content
</div>
<div id="item4">
  some content
</div>

I want to place them so #item1 & #item2 sits next to each other on the first row and #item3 & #item4 next to each other on the second row (forming a square together).

I know how to do this with floats:

#item1, #item3 {
  float: right;
}

but our teacher want's us to use "display: inline-block" for this website. I've tried to find and answer but the only thing I could come up with was to put the items in sets of two:

<div id="content1">
  <div id="item1">
    some content
  </div>
  <div id="item2">
    some content
  </div>
</div>

<div id="content2">
  <div id="item3">
    some content
  </div>
  <div id="item4">
    some content
  </div>
</div>

  #item1, #item2 {
    display: inline-block;
  }

  #item3, #item4 {
    display: inline-block;
  }

And that's not an option since I need to be able to move elements individually by using media queries :/ for example float #item1 in a separate direction on the homepage while #item2 moves elsewhere, I hope you understand what I mean.

EDIT To clearify I want "lemon" to be right under "apple": https://jsfiddle.net/1hj3L018/1/

Upvotes: 0

Views: 1511

Answers (2)

Kenneth
Kenneth

Reputation: 28747

You can use inline-block and a percentage for the width:

div{
    display: inline-block;
    width: 50%;
}

That should make item1 and item2 span the first row and item3 and item4 the second row.

EDIT: That is if you really stick them next to each other, without any whitespace in between. There's a few methods to do that (see Ryan's answer). If you want to keep your formatting here's another trick to do that:

<div id="item1">
  some content
</div><!-- 
--><div id="item2">
  some content
</div><!-- 
--><div id="item3">
  some content
</div><!-- 
--><div id="item4">
  some content
</div>

This works because now the parser see everything between the closing and end tag as an HTML comment instead of a whitespace

Upvotes: 0

RPL
RPL

Reputation: 3637

You could use display: inline-block but you should be aware of the whitespace issue this causes. Here is some info on that.

The code below should achieve the result you seek

div {
  display: inline-block;
  width: 50%;
}
<div id="item1">
  item 1
</div><div id="item2">
  item 2
</div><div id="item3">
  item 3
</div><div id="item4">
  item 4
</div>

Upvotes: 1

Related Questions