html布局的常用的四种实现方式

需求:假设高度默认100px ,请写出三栏布局,其中左栏、右栏各为300px,中间自适应

第一种实现方式:浮动布局

将左右的div宽度设为300px,分别左右浮动,中间盒子不设宽度。注意:先写右边盒子,再写中间盒子,否则先渲染中间盒子,中间盒子会占满该行剩下的宽度,右边盒子只能换行显示,就会出现下面的情况

image

正常的渲染效果如下所示:

image

<style type="text/css">
html,body{
padding:0;
margin:0;
}

.container{
padding:0;
margin:0;
width:100%;
height:100px;
}

.container div{
height:100px;
}

.left{
float:left;
width:300px;
background: green;
}

.right{
float:right;
width:300px;
background: blue;
}

.middle{
background: red;
}
</style>


<body>
<div class="container">
<div class="left">左边</div>
<div class="right">右边</div>
<div class="middle">中间</div>
</div>
</body>
</html>

第二种:绝对定位(position:absolute)
设置父盒子position:relative(相对定位),
三个子盒子position:absolute,
左盒子left:0,
右盒子right:0;
中间盒子left:300px;right:300px

image

<style type="text/css">
html,body{
padding:0;
margin:0;
}

.container{
width:100%;
height:100px;
position:relative;
}

.container div{
height:inherit;
text-align: center;
line-height:100px;
}

.left{
position:absolute;
left:0;
width:300px;
background:blueviolet;
}

.right{
position:absolute;
right:0;
width:300px;
background: yellow;
}

.middle{
position:absolute;
left:300px;
right:300px;
background: gold;
}
</style>

<body>
<div class="container">
<div class="left">左边</div>
<div class="middle">中间</div>
<div class='right'>右边</div>
</div>
</body>

第三种:flex布局
父盒子 display:flex
左右盒子设置宽度:300px
中间盒子flex:1(flex-grow:1 flex-shrink:1 flex-basis:0%)不考虑元素尺寸自由伸缩

image
<style type="text/css">
html,body {
padding: 0;
margin: 0;
}

.container {
width: 100%;
height: 100px;
display: flex;
}

.left {
width: 300px;
background: blueviolet;
}

.right {
width: 300px;
background: yellow;
}

.middle {
flex: 1;
background: gold;
}
</style>


<body>
<div class="container">
<div class="left">左边</div>
<div class="middle">中间</div>
<div class='right'>右边</div>
</div>
</body>

第四种:grid布局
父盒子display: grid;
grid-template-columns:300px auto 300px;(分割成3列,宽度分别为300px auto 300px)
grid-template-rows:100px;(占一行,行高100px)

image
<style type="text/css">
            html,body {
                padding: 0;
                margin: 0;
            }
            
            .container {
                width: 100%;
                display: grid;
                grid-template-columns:300px auto 300px;
                grid-template-rows:100px;
            }
            
            .left {
                background: blueviolet;
            }
            
            .right {
                background: yellow;
            }
            
            .middle {
                background: gold;
            }
        </style>
<body>
<div class="container">
<div class="left">左边</div>
<div class="middle">中间</div>
<div class='right'>右边</div>
</div>
</body>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。