css - 将一个元素与旁边的另一个元素居中
问题描述
以上是我想要实现的,但是它完成了position: absolute;
一些非常奇怪的定位值,这当然没有响应并且看起来很奇怪。我的问题是我只能让父元素居中,而不仅仅是文本。图像也必须与文本对齐。
我一直在寻找几个小时,似乎无法找到解决方案,但我确信这是一个如此简单的解决方案。谢谢!
Codepen: https ://codepen.io/sigurdmazanti/pen/gOxMBem
代码示例:
* {
font-size: 30px;
font-weight: normal;
}
p {
text-align: center;
}
header {
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
h2 {
text-align: center;
}
img {
width: 200px;
height: 200px;
}
.rabbit_absolute {
position: absolute;
right: 540px;
top: 20px;
}
<p>This text is centered</p>
<!-- position absolute -->
<header>
<h2>This text is centered</h2><img src="https://www.freeiconspng.com/uploads/cute-rabbit-png-12.png" class="rabbit_absolute">
</header>
<!-- regular flexbox -->
<header>
<h2>This text is not centered</h2><img src="https://www.freeiconspng.com/uploads/cute-rabbit-png-12.png" class="rabbit_flexbox">
</header>
解决方案
It's a simple trick. First you should put the img
inside the h2
and set position:absolute
on the image
Html:
<header>
<h2>This text is centered<img src="https://www.freeiconspng.com/uploads/cute-rabbit-png-12.png" class="rabbit">
</h2></header>
css:
header{
display: flex;
justify-content: center;
align-items: center;
}
.rabbit{
position: absolute;
}
This way you can center the text in h2
using flexbox and the img
will always stick to the side of the text