You can try this code yourself and find that there is a problem, it is right to the next line.
Why is this? Because float elements cannot exceed the previous non-float element.
The solution is also simple, move the center to the end.
Option two
The above scheme is the center at the end, although the effect can be achieved, but our main content is generally placed in the center, so for SEO is not very friendly, we can find a way to put the center in the front.
<!DOCTYPE html> < html long = "and" > <head> <metacharset="UTF-8"> <metahttp-equiv="X-UA-Compatible"content="IE=edge"> <metaname="viewport"content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #parent { /* This is to prevent height collapse, because the child elements are all floating, separated from the doc stream */ height: 300px; /* The margin-left value is the same as the left width, and the margin-right value is the same as the right width */ margin-left: 300px; margin-right: 300px; } #left, #right, #center { height: 300px; float: left; } #left { background-color: red; width: 300px; } #center { background-color: green; /* auto expands to the same width as parent */ width: 100%; } #right { background-color: grey; width: 300px; } </style> </head> <body> <divid="parent"> <divid="center"></div> <divid="left"></div> <divid="right"></div> </div> </body> </html>
This implementation doesn’t really work because all three are floating, and center fills the entire parent, so left and right will be squeezed to the next line.
Then we need to move left, and because the three are floating, moving left can bring left to the previous line.
<!DOCTYPE html> < html long = "and" > <head> <metacharset="UTF-8"> <metahttp-equiv="X-UA-Compatible"content="IE=edge"> <metaname="viewport"content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #parent { /* This is to prevent height collapse, because the child elements are all floating, separated from the doc stream */ height: 300px; /* The margin-left value is the same as the left width, and the margin-right value is the same as the right width */ margin-left: 300px; margin-right: 300px; } #left, #right, #center { height: 300px; float: left; } #left { background-color: red; width: 300px; /* move the width of the parent element to the left */ margin-left: -100%; /* Move its own width to the left, combine the two and add three child elements that are floating, you can put left in the correct position */ position: relative; left: -300px; } #center { background-color: green; /* auto expands to the same width as parent */ width: 100%; } #right { background-color: grey; width: 300px; } </style> </head> <body> <divid="parent"> <divid="center"></div> <divid="left"></div> <divid="right"></div> </div> </body> </html>