问题:在屏幕中间垂直居中画一个正方形,其边长为屏幕短边的一半。
解析:
- css 单位中的相对长度
- 垂直居中的实现方式
CSS有两种类型的长度单位:相对和绝对。
相对长度单位指定了一个长度相对于另一个长度的属性。对于不同的设备相对长度更适用。
vw | viewpoint width,视窗宽度,1vw=视窗宽度的1% |
vh | viewpoint height,视窗高度,1vh=视窗高度的1% |
vmin | vw和vh中较小的那个 |
vmax | vw和vh中较大的那个 |
<html>
<head>
<title>square-vertical-center</title>
</head>
<body class="body">
<div class="square">
在手机全屏幕中间垂直居中画一个正方形,正方形的边长是屏幕的短边的一半
</div>
</body>
<style type="text/css">
html,
body {
margin: 0;
}
/* 方案一 转换位移*/
.square {
width: 50vmin;
height: 50vmin;
background-color: blue;
position: relative;
left: 50vw;
top: 50vh;
transform: translateX(-50%) translateY(-50%);
font-size: 20px;
color: #ffffff;
text-align: center;
}
/* 方案二 flex布局*/
/* body {
display: flex;
flex-direction: row;
justify-content: center;
}
.square {
width: 50vmin;
height: 50vmin;
background-color: blue;
align-self: center;
font-size: 20px;
color: #ffffff;
text-align: center;
} */
</style>
</html>