CSS-4种布局简单实现

227 阅读2分钟

CSS 4种布局简单实现

左右布局

给所有子元素添加float: left,同时给父元素添加clearfix类,为了解决浮动出现的bug。

html:


<div class="father clearfix">

    <div class="child">元素1</div>

    <div class="child">元素2</div>

    <div class="child">元素3</div>

</div>

CSS:


.clearfix::after{

  content: '';

  display: block;

  clear: both;

}



.child {

  float:left

}

左中右布局

浮动float布局:

左元素: float: left; 右元素: float: right; 中间元素:自动填充

html:


<article class="left-right-center">

        <div class="left">左边</div>

        <div class="right">右边</div>

        <div class="center"><h1>

            浮动float布局:

        </h1> 左元素: float: left; 右元素: float: right; 中间元素:自动填充</div>

    </article>

css:


html *{
            margin: 0;
            padding: 0;
        }
        .left{
            width: 300px;
            height: 100px;
            background-color: #823384;
            text-align: center;
            font-size: 20px;
            color: #fdf6e3;
        }
        .center{
            height: 100px;
            background-color: #d29922;
        }
        .right{
            width: 300px;
            height: 100px;
            background-color: #0c8ac5;
            text-align: center;
            font-size: 20px;
            color: #fdf6e3;
        }
        .float article .left{
            float: left;
        }
        .float article .right{
            float: right;
        }

水平居中

需要的主要css代码有两个,一个为text-align:center(内容居中),另外一个为margin:0 auto;其两个样式需要配合使用才能实现div盒子的居中显示排版。


<style> 
body{ text-align:center} 
.div{ margin:0 auto;width:400px;height:100px;border:1px solid #F00}
/*css注释:为了观察效果设置宽度 边框高度等样式 */
</style> 
</head> 
<body> 
<div class="div"> 
css水平居中实例
</div> 

垂直居中

使用CSS3的弹性布局(flex),设置父元素(这里是指body)的display的值为flex即可

来源于阮一峰老师的博客

html


<style> 
body { width: 100%; height: 100%; margin: 0; padding: 0;}
body {display: flex;align-items: center;/*定义body的元素垂直居中*/         
 justify-content: center;/*定义body的里的元素水平居中*/}       
 .content {width: 300px;height: 300px;background: orange;}
</style>
</head>
<body><div class="content"></div></body>

小技巧 当进行调试时,页面没有任何反应,给该元素加个边框

border: 1px solid red;

背景图片脱离文档流

.topnavbar{
position:fixed;
top:0;
left:0;}

做边框时尽量不要写宽高,再文字上下左右加缺的像素更好

padding的使用

padding: 0px 0px 0px 0px; 顺序上右下左

如何使图片居中

background-position: center(水平) center(垂直)

图片按比例缩放

background-size:cover;(盖住我所有的面积按比例缩放)

脱离文档流

子元素span相对于父元素span定位
子元素position:absolute;
父元素position:relative;