html - 如何在 CSS 中的悬停动作期间居中元素
问题描述
所以我正在学习 CSS,我仍然习惯于能够正确定位所有元素。现在,我有一个 HTML 和 CSS 文件,它绘制了基本上看起来像 Android 机器人的东西。头部有一个动作,如果你将鼠标悬停在它上面,它的宽度就会改变为 300px。问题是眼睛变得不居中。在悬停事件期间如何使眼睛居中?
编辑:奖金问题;在 CSS 文件的 .eyes 部分,我想知道为什么只做display: flex
眼睛的中心。我想我必须将align_items: center
它添加到横轴的中心,但只要做第一个就已经使它居中了。
h1 {
text-align: center;
font-family: 'Roboto', sans-serif;
}
.robots {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.head,
.left_arm,
.torso,
.right_arm,
.left_leg,
.right_leg {
background-color: #5f93e8;
}
.head {
width: 200px;
margin: 0 auto;
height: 150px;
border-radius: 200px 200px 0 0;
margin-bottom: 10px;
}
.eyes {
display: flex;
align-items: center;
}
.head:hover {
width: 300px;
}
.upper_body {
width: 300px;
height: 150px;
display: flex;
}
.left_arm,
.right_arm {
width: 40px;
height: 125px;
border-radius: 100px;
}
.left_arm {
margin-right: 10px;
}
.right_arm {
margin-left: 10px;
}
.torso {
width: 200px;
height: 200px;
border-radius: 0 0 50px 50px;
}
.lower_body {
width: 200px;
height: 200px;
/* This is another useful property. Hmm what do you think it does?*/
margin: 0 auto;
display: flex;
justify-content: center;
}
.left_leg,
.right_leg {
width: 40px;
height: 120px;
border-radius: 0 0 100px 100px;
}
.left_leg {
margin-right: 30px;
}
.left_leg:hover {
-webkit-transform: rotate(20deg);
-moz-transform: rotate(20deg);
-o-transform: rotate(20deg);
-ms-transform: rotate(20deg);
transform: rotate(20deg);
}
.right_leg {
margin-left: 30px;
}
.right_leg:hover {
-webkit-transform: rotate(20deg);
-moz-transform: rotate(20deg);
-o-transform: rotate(20deg);
-ms-transform: rotate(20deg);
transform: rotate(340deg);
}
.left_eye,
.right_eye {
width: 20px;
height: 20px;
border-radius: 15px;
background-color: white;
}
.left_eye {
/* These properties are new and you haven't encountered
in this course. Check out CSS Tricks to see what it does! */
position: relative;
top: 100px;
left: 40px;
}
.right_eye {
position: relative;
top: 100px;
left: 120px;
}
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<h1>Robot Friend</h1>
<div class="robots">
<div class="android">
<div class="head">
<div class="eyes">
<div class="left_eye"></div>
<div class="right_eye"></div>
</div>
</div>
<div class="upper_body">
<div class="left_arm"></div>
<div class="torso"></div>
<div class="right_arm"></div>
</div>
<div class="lower_body">
<div class="left_leg"></div>
<div class="right_leg"></div>
</div>
</div>
</div>
解决方案
只需尝试将您的眼睛定位在 margin- 而不是 position- left:
.left_eye, .right_eye {
width: 20px;
height: 20px;
border-radius: 15px;
background-color: white;
margin: 0 auto; <-- make horizontal margin automatically
}
所以即使你改变元素的宽度,它仍然会居中。