如何在 x 轴和 y 轴中间对齐任何元素?
我只想将数字放在弹性项目的中间,但我只是不知道该怎么做。我尝试了很多方法,但没有一个适用于 Flexbox...这只是我尝试使用 Flexbox 的学习材料,所以我想坚持使用这个显示器。
正如我所说,我尝试了很多方法,因此可能有些东西不需要在那里,对此感到抱歉。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Flex</title>
<style>
* {
margin: 0px;
}
.con {
display: flex;
background-color: aquamarine;
border: 4px solid wheat;
padding: 16px;
height: 511px;
width: 95%;
align-items: center;
justify-content: center;
gap: 8px;
margin: 0px;
}
.i {
height: 60px;
width: 400px;
background-color: red;
border: 4px solid darkslategray;
flex: 1 1 auto;
}
#i2 {
flex: 2 4 auto;
}
p {
position: relative;
vertical-align: middle;
text-align: center;
margin: 0 auto;
width: 20px;
height: 20px;
}
</style>
</head>
<body>
<div class="con">
<div id="i1" class="i"><p>1</p></div>
<div id="i2" class="i"><p>2</p></div>
<div id="i3" class="i"><p>3</p></div>
</div>
</body>
</html>
I just want to put the numbers in the midle of the flex items but I just can't figure out how to do it. I tried many ways but none of them worked with flexbox... It is just a learning material where I experiment with flexbox so I want to stick with this display.
As I said I tried many ways so there might be some things that are not needed to be there, sorry about that.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Flex</title>
<style>
* {
margin: 0px;
}
.con {
display: flex;
background-color: aquamarine;
border: 4px solid wheat;
padding: 16px;
height: 511px;
width: 95%;
align-items: center;
justify-content: center;
gap: 8px;
margin: 0px;
}
.i {
height: 60px;
width: 400px;
background-color: red;
border: 4px solid darkslategray;
flex: 1 1 auto;
}
#i2 {
flex: 2 4 auto;
}
p {
position: relative;
vertical-align: middle;
text-align: center;
margin: 0 auto;
width: 20px;
height: 20px;
}
</style>
</head>
<body>
<div class="con">
<div id="i1" class="i"><p>1</p></div>
<div id="i2" class="i"><p>2</p></div>
<div id="i3" class="i"><p>3</p></div>
</div>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过显示:flex或或位置:绝对来做到这一点
You can do this by display: flex or or position: absolute
发生这种情况是因为您的
元素在 css 中的高度为 60px。因此,它们构成了它们所在块的整个高度。
为每个
元素指定
display: flex;
和align-items: center;.这将使数字在 x 轴和 y 轴上居中。
这是CodePen:https://codepen.io/Juka99/pen/qBVJdNv
This is happening because your
<div class='i'></div>
elements have height of 60px in css. So they are the ones that make the whole height of the block they are inside of.Give each of the
<div class='i'></div>
elementsdisplay: flex;
andalign-items: center;
. This will center the numbers both on x and y axis.Here is the CodePen: https://codepen.io/Juka99/pen/qBVJdNv
也许你可以使用类似 this
我只是在
con
类:Maybe you can use something like this
I just add some extra flex inside
con
class:您可以使用显示:flex;对齐项目:居中;对于 .i 类
you can use display: flex; align-items:center; for .i class