如何垂直对齐一个应该在内容右侧的元素?

问题描述 投票:0回答:3

我遇到了一个问题,就是如何正确对齐句子旁边的 "X "按钮。我使用浮动:右,我认为这就是问题所在,但基本上横幅看起来是这样的。

我如何正确地垂直对齐 "X"?

enter image description here

 <p class="banner-content">
Don't miss out on our special offers during COVID-19. Including <s>£69</s> £40 to take the Foundation Level IT Professional Certification. 
  <span class="close-banner" 
  style="color:black; 
 font-size:1.5em;">&times;</span>
</p>

.close-banner {
    float:right;
    display:inline-block;
    vertical-align: middle;
    color: black;
}

.banner-content{
    padding: 1em;
    padding-bottom:0;
    font-size: large;
    color: black;
    font-weight: bold;
    text-align: center;
    width:100%;
}
html css
3个回答
0
投票

你可以给容器 position: relative; 并给予 position: absolute; 到x,并使用 toptransform 以将其定位在中间。

<p class="banner-content">
  Some text here 
  <span class="close-banner">&times;</span>
</p>

.banner-content {
  position: relative;
  text-align: center;
  width: 100%;
}
.close-banner {
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
}

解释。

因为母体被设置为 position relative; 而孩子是 position absolute;子代以其父代为向导。top: 50%; 将子代的顶部设置在父代的垂直中间位置,并将子代的顶部设置在父代的垂直中间位置。transform: translateY(-50%); 将孩子高度的一半上移,使其准确定位在中心位置。下面是victorw999的一张图片,可以说明这个问题。top: 50%; left: 50%; put the top left corner at the centre. transform: translate(-50%, -50%); shifts the centre of the child to the centre of its parent.

© www.soinside.com 2019 - 2024. All rights reserved.