注意:原始帖子已被其用户删除,并且我发现它可能有用,因此我重新发布了它。
矩形应旋转-90度,并在屏幕左侧垂直居中。如下图所示。
如果可能,应仅使用HTML和CSS。
问题是,首先旋转元件,这使它居中更加困难。
堆栈片段
html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
font-size: 16px;
font-family: Arial, sans-serif;
}
* {
box-sizing: border-box;
}
body>div {
position: fixed;
top: 50%;
left: 0;
background-color: #FF0000;
color: white;
font-weight: bold;
padding: 10px;
-webkit-transform: rotate(-90.0deg);
-moz-transform: rotate(-90.0deg);
-ms-transform: rotate(-90.0deg);
-o-transform: rotate(-90.0deg);
transform: rotate(-90.0deg);
}
<div>Lorem Ipsum</div>
最佳答案
要更好地控制旋转,并且更容易将其左对齐和垂直居中,请同时使用transform-origin
和transform
。
首先,通过在transform-origin: left top;
上添加div
使其左/上角为旋转中心。
其次,通过组合rotate
和translate
,将其自身宽度的一半移到左侧(translateX(-50%)
),然后将其逆时针rotate(-90.0deg)
旋转90度。
注1;当使用多个<transform-function>
值时,它们从右到左执行,在下面的示例中表示它以translateX
开头。
笔记2;我临时删除了前缀属性,因此您需要将其重新添加。
堆栈片段
html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
font-size: 16px;
font-family: Arial, sans-serif;
background-color: #ccc;
}
* {
box-sizing: border-box;
}
body>div {
position: fixed;
top: 50%;
left: 0;
background-color: #FF0000;
color: white;
font-weight: bold;
padding: 10px;
transform-origin: left top;
transform: rotate(-90.0deg) translateX(-50%);
}
<div>Lorem Ipsum</div>
发表评论后更新。
这是4个小提琴,显示了4个步骤,希望可以更清楚地说明其工作原理:
Step 1-Step 2-Step 3-Step 4
这是一个动画,显示它是如何运动的,并希望使其工作原理更加清楚:
html, body {
margin: 0;
font-size: 16px;
font-family: Arial, sans-serif;
}
.faked-body div {
position: absolute;
top: 50%;
left: 0;
background-color: #FF0000;
color: white;
font-weight: bold;
padding: 10px;
transform-origin: left top; /* the rotation center is moved to black circle */
transform: rotate(0)
translateX(0);
animation: the-div 3s 1s forwards;
}
@keyframes the-div {
0% { transform: rotate(0)
translateX(0);
}
50% { transform: rotate(0)
translateX(-50%); /* move to left */
}
100% { transform: rotate(-90deg) /* rotate 90 degree */
translateX(-50%);
}
}
/* styling/info for this demo */
.faked-body div::before {
content: '';
position: absolute;
top: -10px;
left: 0;
transform: translateX(-50%);
width: 20px;
height: 20px;
border-radius: 50%;
background-color: black;
animation: the-spot 1.5s 1s forwards;
}
.faked-body {
position: relative;
margin: 10px 60px;
width: 440px;
height: 200px;
background-color: #ccc;
font-size: 14px;
}
.faked-body::before {
content: 'The gray area represents the body so we can see how the "Lorem Ipsum" element moves';
color: #666;
}
.faked-body::after {
content: 'The black spot show where the rotation center is';
color: #222;
position: absolute;
bottom: 0; left: 0;
}
@keyframes the-spot {
0% { left: 0;
}
100% { left: 50%;
}
}
<div class="faked-body">
<div>Lorem Ipsum</div>
</div>