1 子元素不能布满剩余的空间的问题
1.1 整体页面不能布满整个空间
第一步:去掉所有元素的padding和margin(可不做):
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
第二步:设置body,html的height为100%
body,html{
width: 100;
height: 100%;
}
第三步:设置主div的height为100%
#app {
height: 100%;
display: flex;
flex-direction: column;
}
第四步:设置剩下的div的高度为100%
1.2 局部div不能布满整个空间
第一步:设置父元素
.test-container {
display: flex;
flex-direction: column;
height: 100%;
}
第二步:设置剩余的元素的样式
{
flex: 1;
}
1.3 案例
<template>
<div class="test-container">
<div class="test-item">
<button @click="close">close</button>
<button @click="success">success</button>
</div>
<div class="test-item"></div>
<div class="test-item"></div>
<div class="test-item"></div>
<div class="test-item"></div>
</div>
</template>
<script>
export default {}
</script>
<style scoped>
.test-container {
background-color: blue;
display: flex;
flex-direction: column;
height: 100%;
}
.test-item {
height: 200px;
background-color: brown;
margin: 10px;
}
.test-item:nth-child(5){
flex: 1;
}
</style>
2 添加滚动条
添加滚动条的前提条件是父元素是固定值,那么有两种情况:第一种情况是父元素的高度是固定值,第二种情况是父元素是100%
第一种比较好解决,只需要添加overflow,当然除了下面的scroll还可以设置其他的属性字段,视具体使用场景确定。
overflow: scroll;
第二种情况
需结合第一个常见样式问题,首先这个父元素需要铺满剩余空间。不能是靠子元素去撑开,不然overflow不起作用。
3 div居中
3.1 左右居中
子元素需要有固定宽度,设置margin:0 auto
<template>
<div class="test-container">
<div class="test-item">
</div>
</div>
</template>
<script>
export default {}
</script>
<style scoped>
.test-container {
background-color: blue;
display: flex;
flex-direction: column;
height: 100%;
}
.test-item {
height: 200px;
width: 600px;
background-color: brown;
margin: 0 auto;
}
</style>
3.2 左右上下居中
方法一:采用flex布局,并且设置justify-content和align-items的属性为center
<template>
<div class="test-container">
<div class="test-item">
</div>
</div>
</template>
<script>
export default {}
</script>
<style scoped>
.test-container {
background-color: blue;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
}
.test-item {
height: 200px;
width: 600px;
background-color: brown;
}
</style>
方法二:采用盒子布局,并通过margin来设置
<template>
<div class="test-container">
<div class="test-item">
</div>
</div>
</template>
<script>
export default {}
</script>
<style scoped>
.test-container {
position: relative;
background-color: blue;
height: 100%;
}
.test-item {
position: absolute;
top: 50%;
left: 50%;
height: 200px;
width: 600px;
margin-top: -100px;
margin-left: -300px;
background-color: brown;
}
</style>
方法三:采用盒子布局,并通过transform来设置
<template>
<div class="test-container">
<div class="test-item">
</div>
</div>
</template>
<script>
export default {}
</script>
<style scoped>
.test-container {
position: relative;
background-color: blue;
height: 100%;
}
.test-item {
position: absolute;
top: 50%;
left: 50%;
height: 200px;
width: 600px;
transform: translate(-300px,-100px);
background-color: brown;
}
</style>