【CSS】flex实现多⾏多列的多种⽅式
灵活变通:通过百分⽐和折⾏来实现,是n列就把百分⽐变为100/n(%),如果是3列,那么可以把50%改成33.333%,如果是4列,那么改成25%,依次类推,
下⾯是2⾏2列的多种写法实现
⼀.⽗容器设置为flex布局,并允许折⾏
.flex-outer{
display: flex;
flex-wrap: wrap;
}
⼆.⼦容器设置样式
.flex-outer article{
background: limegreen;
border: 1px solid #eee;
box-sizing: border-box;
color: #fff;
padding: 15px;
}
三.多种⽅法给每个⼦容器设置50%的宽度,实现2⾏2列⽅法1 :flex合并属性 flex: 1 0 50%;
/* flex合并属性 */
.flex-outer.flex-attr article{
flex: 1 0 50%;
}
html结构
<h3><pre><span>1.flex合并属性 </span><span>flex: 1 0 50%;</span></pre></h3>  <section class="flex-outer flex-attr">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
</section>
⽅法2 : 基准属性 flex-basis: 50%;
/* flex-basis */
.flex-outer.flex-basis article{
flex-basis: 50%;
}
html
<h3><pre><span>2.基准属性</span><span>flex-basis: 50%;</span></pre></h3>    <section class="flex-outer flex-basis">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
</section>
⽅法3: 设置宽度 width: 50%;
/* 设置width */
.flex-outer.width-attr article{
width: 50%;
}
html:
<h3><pre><span>3.设置width</span><span>width: 50%;</span></pre></h3>
<section class="flex-outer width-attr">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
</section>
完整实例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>flex实现两⾏两列</title>
<style>
.flex-outer {
.
flex-outer {
display: flex;
flex-wrap: wrap;
}
.flex-outer article {
background: limegreen;
border: 1px solid #eee;
box-sizing: border-box;
color: #fff;
padding: 15px;
}
/
* flex合并属性 */
.flex-outer.flex-attr article  {
flex: 1 0 50%;
}
/* flex-basis */
.flex-outer.flex-basis article {
flex-basis: 50%;
}
/* 设置width */
.flex-outer.width-attr article {
width: 50%;
}
pre {
display: flex;
justify-content: space-between;
}
</style>
</head>
<body>
<h3><pre><span>1.flex合并属性 </span><span>flex: 1 0 50%;</span></pre></h3>    <section class="flex-outer flex-attr">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
</section>
<h3><pre><span>2.基准属性</span><span>flex-basis: 50%;</span></pre></h3>    <section class="flex-outer flex-basis">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
cssclass属性
</section>
<h3><pre><span>3.设置width</span><span>width: 50%;</span></pre></h3>
<section class="flex-outer width-attr">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
</section>
</body>
</html>
在线预览

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。