实现类
...大约 2 分钟
垂直居中
水平垂直居中
- flex布局:父元素(display:flex;justify-content:center;align-items:center)
- 绝对定位:父元素(position:relative)子元素(position:absolute) 知道宽高(top:50%;left:50%;margin-top:-[高/2]px;margin-left:-[宽/2]px)
不知道宽高(top:50%;left:50%;transform:translate(-50%,-50%)【左右,上下】)
水平居中
- flex布局:父元素(display:flex;justify-content:center;)
- 绝对定位:同水平垂直居中方法
- 行内元素:父元素(text-align:center)
- 给定宽度的:子元素(margin:0 auto)
垂直居中
- flex布局:父元素(display:flex;align-items:center)
- flex布局:父元素(display:flex;)子元素(margin:auto 0)
- 绝对定位:同水平垂直居中方法
- 纯文本:父元素(line-height)
两边固定,中间自适应
flex布局
三个div外面包裹一个父元素div,将父元素box设为 display:flex
,两边div设置宽度,中间div设置flex:1
<template>
<div class="parent">
<div class="left">左</div>
<div class="center">中</div>
<div class="right">右</div>
</div>
</template>
<style lang="scss" scoped>
.parent {
display: flex;
}
.left {
background: blue;
width: 200px;
}
.center {
background: green;
flex: 1;
}
.right {
background: yellow;
width: 200px;
}
</style>
圣杯
- 绝对定位 + 父padding
父元素包裹三个子元素,父元素 position: relative; padding: 0 200px;
子元素设置宽度、左右绝对定位,中间元素 width: 100%;
<template>
<div class="parent">
<div class="center">中</div>
<div class="left">左</div>
<div class="right">右</div>
</div>
</template>
<style lang="scss" scoped>
.parent {
position: relative;
padding: 0 200px;
}
.left {
background: blue;
width: 200px;
position: absolute;
left: 0;
top: 0;
}
.center {
background: green;
width: 100%;
}
.right {
background: yellow;
width: 200px;
position: absolute;
right: 0;
top: 0;
}
</style>
双飞翼
中间div外面再包一个div,三个div中间的在前,左右中外div都float:left,左margin-left:-100%,右margin-left:-200px,中div设置margin:0 200px,中外div设置width:100%
<template>
<div class="parent">
<div class="centerOut float">
<div class="center">中</div>
</div>
<div class="left float">左</div>
<div class="right float">右</div>
</div>
</template>
<style lang="scss" scoped>
.float {
float: left;
}
.left {
background: blue;
width: 200px;
margin-left: 100%;
}
.centerOut{
width: 100%;
}
.center {
background: green;
margin: 0 200px;
}
.right {
background: yellow;
width: 200px;
margin-left: -200px;
}
</style>
都是三栏布局,优先展示渲染中间部分。
圣杯: 正常情况下是没有问题的,但是特殊情况下,当中间部分宽度小于左盒子的时候 就会发生布局混乱。
双飞翼: CSS样式代码更简洁,但是多加了一层dom节点。
0.5px边框
阴影box-shadow
能解决一些简单的场景
box-shadow: 0 0 0 0.5px rgb(0, 22, 33)
伪元素 + transform
适合各种场景
<template>
<div class="my-box"></div>
</template>
<style lang='scss' scoped>
.my-box {
width: 200px;
height: 200px;
border-radius: 10px;
&::after {
position: absolute;
left: 0;
bottom: 0;
width: 200%;
height: 200%;
content: "";
display: block;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 20px;
transform: scale(0.5);
transform-origin: left bottom;
}
}
</style>
Powered by Waline v2.15.5