There are two main ways to solve the Holy Grail layout problem with Flex layout.
- Method 1: Set the parent element
display:flex
The left and right boxes 1 and 3 in the child element are set to fixedwidth
andheight
Instead of setting width for the middle subbox, useflex: 1
Let the middle child box 2 divide up the space left by the parent element, where 1 means the width of the parent box -1 width-3 width. Examples of effects:
HTML structure:
<section>
<div>1</div>
<div>2</div>
<div>3</div>
</section>
Copy the code
CSS styles:
* { margin: 0; padding: 0; } section { display: flex; width: 60%; height: 80px; margin: 50px auto; background-color: pink; } section div:nth-child(1),section div:nth-child(3) { width: 80px; height: 80px; background-color: skyblue; } /* Section div:nth-child(2) {flex: 1; height: 80px; background-color: green; }Copy the code
- Method 2: Fully use flex properties to set on boxes 1, 2 and 3, so that box 2 occupies more points than box 1 and 2. For example, here we can set the total number of copies to 6, left and right boxes to 1, middle boxes to 4, 1, 2 and 3 ratio: 1:4:1, effect picture:
HTML structure:
<div class="box">
<span>1</span>
<span>2</span>
<span>3</span>
</div>
Copy the code
CSS styles:
.box {
display: flex;
width: 60%;
height: 80px;
background-color: pink;
margin: 0 auto;
}
.box span {
flex: 1;
}
.box span:nth-child(2) {
flex:4;
background-color: purple;
}
Copy the code
Flex layouts are a great solution to problems like the JD search bar, which is a typical Holy grail layout,
Another layout method can refer to my previous post # postion: Absolute# positioning attribute to solve the grail layout problem, this is more troublesome than Flex, not as simple and clean as Flex, I recommend using Flex layout in the Grail layout problem.
Finally complete code: welcome to thumb up share | | | collection. ❥ (^ -) ❥ (^ -) ❥ (^ _ -)
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Word-wrap: break-word! Important; "> < span style> * {margin: 0; padding: 0; } section { display: flex; width: 60%; height: 80px; margin: 50px auto; background-color: pink; } section div:nth-child(1),section div:nth-child(3) { width: 80px; height: 80px; background-color: skyblue; } /* Section div:nth-child(2) {flex: 1; height: 80px; background-color: green; } .box { display: flex; width: 60%; height: 80px; background-color: pink; margin: 0 auto; } .box span { flex: 1; } .box span:nth-child(2) { flex:4; background-color: purple; } </style> </head> <body> <section> <div>1</div> <div>2</div> <div>3</div> </section> <div class="box"> <span>1</span> <span>2</span> <span>3</span> </div> </body> </html>Copy the code