微信小程序开发入门(四)

Float页面布局

  使用float和clear属性进行布局,利用margin属性实现块元素(组件)水平居中对齐

float属性

  浮动的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止。

Float属性的合法值 

  

 clear属性

  清除浮动。

clear属性的合法值

  

利用margin属性实现水平居中对齐
  如果要实现块元素的水平居中对齐,可以通过让 margin左右边距为auto的方式来实现,这样块元素将
平均分配左右边距,从而实现水平居中对齐。

<!--index.wxml-->
<view class='box'>
  <view class="title">Float页面布局</view>

  <view class="bg1">
    <view class='box1'>box1</view>
    <view class='box2'>box2</view>
    <view class='box3'>box3</view>
    <view class='box4'>box4</view>
  </view>

  <view class='bg2'>
    <view class='header'>header</view>
    <view class='leftBar'>leftBar</view>
    <view class='main'>main</view>
    <view class='rightBar'>rightBar</view>
    <view class='footer'>footer</view>
  </view>
</view>
/**app.wxss**/
.box{
  border: 1px solid silver;
  margin: 20rpx;
  padding: 20rpx;
}
.title{
font-size: 25px;
text-align: center;
margin-bottom: 15px;
color: red;
}
/* pages/index/index.wxss */

.bg1 {
  /* 背景1 */
  height: 240px;/*高度*/
   200px;/*宽度*/
  margin: 10px auto; /* 上下边距为10px,左右边距平均分配(实现水平居中对齐) */
}

.box1 {
  /* 背景1中的第1个颜色块 */
   100px;
  height: 80px;/*240中的80*/
  background-color: red;
  margin: 0 auto;/* 上下边距为0,bg1内水平居中对齐*/
}

.box2 {
  /* 背景1中的第2个颜色块 */
   100px;/**box2+box3宽度200,占满了整个bg1的宽度*/
  height: 80px;/*240中的80*/
  background-color: yellow;
  float: left; /* 左浮动;默认情况下每个view另起一行,因此box2换到了下一行,左浮动:直接靠到bg1的左边界 */
}

.box3 {
  /* 背景1中的第3个颜色块 */
   100px;
  height: 80px;
  background-color: gold;
  float: right; /* 右浮动,紧靠在bg1的右侧 */
}

.box4 {
  /* 背景1中的第4个颜色块 */
   100px;
  height: 80px;/*240中的80*/
  background-color: greenyellow;
  margin: 0 auto;
  clear: both; /* 清除左右两边浮动;左右浮动不起作用,box4单独在一个view,所以换到了下一行 */
}

.bg2 {
  /* 背景2 */
  height: 400rpx;
  text-align: center;/* 整个区域所有的文本水平居中 */
  margin: 10px auto;/* bg1有个边距10,bg2有个10,边距合并,最后的结果还是10 */
}

.header {
  /* 头部标题区 */
  line-height: 100rpx; /* 定义行高,同时实现文字垂直方向居中对齐 */
  background-color: red;
}

.leftBar {
  /* 左边导航区 */
   20%;
  line-height: 200rpx; /* 定义行高,同时实现文字垂直方向居中对齐 */
  background-color: yellow;
  float: left; /* 左浮动 */
}

.main {
  /* 中间内容区 */
   60%;
  line-height: 200rpx;
  background-color: rgb(157, 255, 0);
  float: left; /* 左浮动 ,紧靠在leftBar的右边界 */
}

.rightBar {
  /* 右边内容区 */
   20%;
  line-height: 200rpx;
  background-color: yellow;
  float: right; /* 右浮动 ,紧靠在bg2的右边界*/
}

.footer {
  /* 底部版权区 */
  line-height: 100rpx;
  background-color: red;
  clear: both;
}

原文地址:https://www.cnblogs.com/suitcases/p/13346564.html