gpt4 book ai didi

css - 将伪元素对齐到右侧和垂直中心

转载 作者:技术小花猫 更新时间:2023-10-29 11:06:06 27 4
gpt4 key购买 nike

我需要图像显示在最右侧,而文本保持在左侧。我还需要保持垂直对齐。

我试图在 ::after 伪元素上 float ,但它破坏了垂直对齐。有什么想法吗?

JSFiddle

.holder{
width: 100%;
background: tomato;
height: 200px;
line-height: 200px;
}

.holder::after{
content: "";
border: 1px solid red;
background: transparent url('my-img.jpg') no-repeat;
width: 30px;
height: 30px;
display: inline-block;
}
<div class="holder">
Section 1
</div>

最佳答案

  1. .holder 元素上,将其设置为 position: relative 以便任何子元素或伪元素都可以相对于自身定位。
  2. 在伪元素上设置position: absolute。这将允许您将其精确定位在 .holder 中。
  3. right: 0 添加到伪元素,使其移动到 .holder 的右边缘。
  4. 为了使伪元素垂直居中,我们设置属性 top: 50%。这会将它向下移动一半 .holder。此时的问题是它仍然没有居中,因为伪元素的顶部边缘位于中心。所以我们需要将伪元素向上移动其自高度度的一半。我们可以采用以下两种方式之一:

方法一:负边距

因为我们知道伪元素的高度 (30px),所以我们可以像这样简单地设置 -15px 的上边距:margin-top: - 15px;.

这是一个例子:

.holder{
width: 100%;
background: tomato;
height: 180px;
line-height: 180px;
position: relative;
}

.holder::after{
content: "";
background: blue;
width:30px;
height: 30px;
position: absolute;
right: 0;
top: 50%;
margin-top: -15px;
}
<div class="holder">
Section 1
</div>


方法二:翻译

如果我们不知道元素的高度,我们可以使用 transform 属性的 translate 值将伪元素向上移动其高度的 50%,如下所示:transform: translateY(-50%) ;(您可能需要提供浏览器前缀才能使其在所有浏览器中正常工作)。

这是一个例子:

.holder{
width: 100%;
background: tomato;
height: 180px;
line-height: 180px;
position: relative;
}

.holder::after{
content: "";
background: blue;
width:30px;
height: 30px;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
}
<div class="holder">
Section 1
</div>

关于css - 将伪元素对齐到右侧和垂直中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com