Div problems after float left

I am trying to place two divs horizontally, but the content of the second div exceeds the height of the first, 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; } 

As a result, I want:

enter image description here

but this is what I get:

enter image description here

+4
source share
4 answers

Why not make the background of the container the same color 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; } 
+6
source

Although float is commonly used for such layout purposes, it was originally designed for float text elements. This is the reason why floating divs behave in a strange way when they are not familiar with it.

Besides the problems of text formatting, there is actually another problem when you want two floating elements to have the same automatic height. This can be achieved much better by using the display property with table and table-cell .

Look at this:

CSS for dynamic HTML layout with non-fixed columns?

Or just grab a fiddle:

http://jsfiddle.net/TfuTE/

+2
source

I think the .container to constraint has a specific background-color can be cumbersome. I suggest using display: table for the parent and display: table-cell for children to get rid of this problem.

Just add the following lines to your stylesheet:

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

Here is the JSBin Demo

+1
source

if you make an element with a block float element, your element will not be 100% high and wide, but the size with the content or larger than you set it with css.

you can give it height using css

you can give a yellow div a margin-left: 104px

0
source

Source: https://habr.com/ru/post/1487878/


All Articles