我想要做的是讓一個文本元素居中,然后在它旁邊放一個影像。

以上是我想要實作的,但是它是用position: absolute;一些非常奇怪的定位值完成的,當然沒有回應并且看起來非常奇怪。我的問題是我只能讓父元素居中,而不僅僅是文本。影像還必須緊挨著文本對齊。
我已經搜索了幾個小時,似乎找不到解決方案,但我確定這是一個簡單的解決方法。謝謝!
代碼筆: 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>
uj5u.com熱心網友回復:
我會做的更簡單一點:
h2通過將文本inline-block置于具有text-align: center.
然后把影像變成 的h2,適用position: relative于h2(=錨絕對定位的兒童)和position: absolute的形象,這相對于H2的位置吧。現在您只需要選擇 與影像大小相關的負數top和right值(將其移到父級之外) - 見下文。
* {
font-size: 30px;
font-weight: normal;
}
header {
text-align: center;
}
h2 {
display: inline-block;
position: relative;
}
img.rabbit {
width: 50px;
height: 50px;
position: absolute;
right: -50px;
top: -10px;
}
<header>
<h2>This text is centered<img src="https://www.freeiconspng.com/uploads/cute-rabbit-png-12.png" class="rabbit"></h2>
</header>
uj5u.com熱心網友回復:
嘗試一些簡單的事情:
* {
font-size: 30px;
font-weight: normal;
}
.cntr {
display: flex;
justify-content: center;
align-items: center;
}
img {
width: 50px;
height: 50px;
}
<header>
<div class="cntr">
<h2>This text is centered</h2>
<img src="https://www.freeiconspng.com/uploads/cute-rabbit-png-12.png" class="rabbit_absolute">
</div>
</header>
uj5u.com熱心網友回復:
這是一個簡單的技巧。首先你應該把img里面的h2
和設定position:absolute在影像上
網址:
<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;
}
這樣,您就可以居中文本中h2使用Flexbox的和img將始終堅持文本的側
uj5u.com熱心網友回復:
您可能會在 flexbox 中使用邊距:
* {
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;
margin:0 50px;
}
img {
width: 50px;
height: 50px;
margin:0 0 0 -50px;
}
<p>This text is centered</p>
<header>
<h2>This text is centered</h2><img src="https://www.freeiconspng.com/uploads/cute-rabbit-png-12.png" class="rabbit_flexbox">
</header>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/326584.html
下一篇:適合容器的內容
