大家好,又见面了,我是你们的朋友全栈君。
由于div默认是没有高度的,如果设置了高度,默认是从左到右,从上到下的顺序来排布;
如果要做垂直居中,就需要计算div控件的高度,如果内容变多或者变少,又会导致定位不准确,因此,最稳妥的办法就是让浏览器自己去根据div的高度居中显示
设为 Flex 布局以后,子元素的float、clear和vertical-align属性将失效。
flex-direction
属性决定主轴的方向(即项目的排列方向)align-items
属性定义项目在交叉轴上如何对齐。align-content
属性定义了多根轴线的对齐方式。如果项目只有一根轴线,该属性不起作用。order
属性定义项目的排列顺序。数值越小,排列越靠前,默认为0。flex-grow
属性定义项目的放大比例,默认为0,即如果存在剩余空间,也不放大。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style> .mycontainer{
height: 200px; width: 200px; border: 1px solid red; /* flex样式呈现*/ display: flex; /*垂直排列*/ flex-direction: column; align-items:center;/*由于flex-direction: column,因此align-items代表的是水平方向*/ justify-content: center;/*由于flex-direction: column,因此justify-content代表的是垂直方向*/ } </style>
<body>
<div class="mycontainer">
<div class="">我是标题</div>
<div class="">我是内容</div>
</div>
</body>
</html>
如果设置了
flex-direction: column,则 justify-content的水平居中 就变为了垂直方向上的,align-items就变为了水平方向上了,这点必须要注意
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
.mycontainer{
height: 200px;
width: 200px;
border: 1px solid red;
display: flex;
align-items: center; // 垂直居中,针对的是mycontainer类下面的子元素,不包含“孙子”元素
justify-content: center; // 水平居中,针对的是mycontainer类下面的子元素,不包含“孙子”元素
}
</style>
<body>
<div class="mycontainer">
<div>
<div class="">我是标题</div>
<div class="">我是内容</div>
</div>
</div>
</body>
</html>
align-items是针对子元素的垂直方向对齐方式,justify-content是针对子元素的水平方向对齐方式
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/130522.html原文链接:https://javaforall.cn