Last year, when I was interviewing for a front-end engineer, I was asked a question –> To achieve a three-column layout with CSS, how many can you write? When I heard how many, I was just a head of water, and I thought I could do just one.
- The first is absolute positioning
.fater{ position:relative; // The parent element sets the absolute position min-height:100px; }. Item {height:100px; // Set the height of each element without seeing it position:absolute; }. Left {left:0; // Width :200px; background-color:black; } .center{ left:200px; // Because the width of the left element is 200px, the distance to the left is 200px right:150px; // The width of the right element is 150px, and the distance is 150px background-color:blue; // There is no width set for this box, can it be displayed? Yes, because the box will be opened by default. } .right{ right:0; // Because it is the right-most element, it is 0px from the right side width:150px; background-color:red; } <div class="father"> <div class="item left"></div> <div class="item center"></div> <div class="item right"></div> </div>Copy the code
- Note the second way to float: the.center element is rendered last
.item{ height:100px; // Set the height of each element to 100px}. Left {float:left; // Float to the left width:200px; background-color:black; } .center{ margin:0 150px 0 200px; Margin: top right bottom left background-color:blue; } .right{ float:right; // Float to the right width:150px; background-color:red; } <div class="item left"></div> <div class="item right"></div> <div class="item center"></div>Copy the code
The.center element has no width, and the.center element is a single line, margin-left:200px; margin-right:150px; What’s left in the middle is its width, and if the dot center is rendered not last but before the dot right element it will squeeze the dot right element onto the next line instead of creating a three-column layout
Abnormal effects are shown here.
Normal effect is shown as follows:
- The third kind of elastic box
.item{ height:100px; } .father{ display:flex; }. Left {width:200px; background-color:blue; } .center{ flex:1; // Flex is a compound property. Flex :1 can also be written as flex-grow, flex-shrink, background-color:black; } .right{ width:200px; background-color:red }Copy the code
If you like it, click a thumbs-up 👍