CSS的几种布局实现

2018-08-01  本文已影响0人  RookieD

左右布局

这个布局比较简单,直接使用float就可以实现

.left {
  height: 100px;
  border: 1px solid red;
  float: left;
  width: 50%;
/* 加上box-sizing是为了整个盒模型宽度计算方便 */
  box-sizing: border-box;
}

.right {
  height: 100px;
  border: 1px solid green;
  float: left;
  width: 50%;
  box-sizing: border-box;
}

左中右布局

.left {
  height: 100px;
  border: 1px solid red;
  float: left;
  width: 30%;
  box-sizing: border-box;
}

.middle {
  height: 100px;
  border: 1px solid yellow;
  float: left;
  width: 30%;
  box-sizing: border-box;
}

.right {
  height: 100px;
  border: 1px solid green;
  float: left;
  width: 30%;
  box-sizing: border-box;
}
<div class="wrapper">
    <div class="left">left</div>
    <div class="middle">middle</div>
    <div class="right">right</div>
</div>

<!-- font-size相关的代码是为了去除inline-block元素之间的间隙 -->
.wrapper {
  text-align: center;
  font-size: 0px;
}

.left {
  display:inline-block;
  border: 1px solid red;
  font-size: 14px;
}

.middle {
  display:inline-block;
  border: 1px solid yellow;
  font-size: 14px;
}

.right {
  display:inline-block;
  border: 1px solid green;
  font-size: 14px;
}

水平居中

div {
  /* 必须指定宽度才能生效 */
  width: 100px;
  margin: 0 auto;
}
div {
  height: 100px;
  width: 100px;
  border: 1px solid red;
  margin-left: 50%;
  position: relative;
  transform: translateX(-50%);
}

垂直居中

<div class="wrapper">
    <div class="inner"></div>
</div>

.wrapper {
  height: 200px;
  border: 1px solid red;
  position: relative;
}

.inner {
  height: 50px;
  width: 50px;
  border: 1px solid blue;
  position: absolute;
  top: 100px;
  transform: translateY(-50%);
}

小技巧

上一篇下一篇

猜你喜欢

热点阅读