6

I'm trying to place two div horizontally, but one the content of the second div exceeds the height of the first one i get bad results:

Here is my Html code:

<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="mystyle.css"></head>
<body>

<div class="container">
<div class="yellow">sometext</div>
<div class="green">more text here more text here more text here more text here more     text here more text here more text here more text here more text here more text     here </div>
<div class="spacer"></div>
</div>
</body>

and this is my Css:

.yellow {
background-color: yellow;
margin: 2px;
float: left;
width: 100px;
text-align: center;
}

.green{
background-color: #00ff00;
      }

.container {
width: 30%;
}

.spacer {
 clear: both;
}

The result i want is this:

enter image description here

but this is what i get:

enter image description here

Hossam Oukli
  • 1,296
  • 3
  • 19
  • 42

4 Answers4

8

Why not make the container background the same colour as your first div and change the CSS to:

JSFiddle here

.yellow {
background-color: #00ff00;
margin: 2px;
float: left;
width: 100px;
text-align: center;
}

.green{
background-color: yellow;
    overflow: hidden;    <-- added
      }

.container {
width: 30%;
    background-color: #00ff00;  <-- added
}

.spacer {
 clear: both;
}
Tanner
  • 22,205
  • 9
  • 65
  • 83
  • clear: both for me did the trick to avoid a Footer div getting messed with float:left before it – Solano Jul 26 '15 at 01:25
2

Although float is commonly used for layout purposes like this, it was originally designed to float text elements. This is the reason for why floated divs behave in a strange manner when ones not familiar with it.

Beside the text formatting issues there is actually another difficulty when you want two floated elements have the same automatic height. This could be achieved much better by using the display property with table and table-cell.

Have a look at this:

CSS for HTML dynamic layout with not fixed columns?

Or just take the regarding fiddle:

http://jsfiddle.net/TfuTE/

Community
  • 1
  • 1
conceptdeluxe
  • 3,753
  • 3
  • 25
  • 29
1

I think restricting .container to has a specific background-color may be cumbersome. I suggest using display: table for parent element and display: table-cell for children to get rid of this issue.

Just add following lines in your stylesheet:

.container {
  display: table;
  height: 100%;
}

.container > div {
  display: table-cell;
  height: inherit;
  vertical-align: top;
}

Here is a JSBin Demo

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
0

if you make a blocklevel element float your element won't be height and width 100% but as big as it's content, or as big as you set it with css.

you could give it a height with css

you could give the yellow div a margin-left: 104px

helle
  • 11,183
  • 9
  • 56
  • 83