如何将<p>中的<span>右对齐并保持<p>中文本居中?(HTML)

3

如果没有视觉参考,很难提出这个问题,所以我在下面(以及代码片段中)附上了图片。 我想实现两件事:

  1. 将蓝色 <span> 圆圈靠右对齐到黄色 <p> 盒子内
  2. 使文本保持在 <p> 盒子居中,与蓝色圆圈无关

这是我的代码:

.circle {
  height: 20px;
  width: 20px;
  background-color: blue;
  border-radius: 50%;
  display: inline-block
 }
 
 .box {
  background-color: yellow; 
  height: 30px; 
  width: 500px; 
  text-align: center; 
  margin: 10px
 }
 
<p class='box'>This is centered</p>

<p class='box'>This is not<span class='circle'></span></p>

我对HTML不是特别熟悉,但我尝试为圆形做align-self: right,但没有任何反应。 不确定该怎么做。

这是我想要实现的效果图片:

enter image description here

2个回答

3

只需要将浮动设置为右侧,并添加外边距即可居中

.circle {
  height: 20px;
  width: 20px;
  background-color: blue;
  border-radius: 50%;
  display: inline-block;
  float: right;
  margin: 5px;
}

.box {
  background-color: yellow;
  height: 30px;
  width: 500px;
  text-align: center;
  margin: 10px;
  box-sizing: border-box;
}

.box2 {
  padding-left: 30px; /* circle width (20px) + circle margin-left (5px) + margin-right (5px) = 30px */
}
<p class='box'>This is centered</p>

<p class='box box2'>This is not<span class='circle'></span></p>


但是在你的示例中,第二个文本没有居中。 - doğukan
更新并调整了一些填充。 - DCR
我简化了你的代码。 - doğukan
不错,看起来不错。 - DCR

1
你可以使用绝对定位。

.circle {
  height: 20px;
  width: 20px;
  background-color: blue;
  border-radius: 50%;
  display: inline-block;
  /* added */
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 10px;
}

.box {
  background-color: yellow;
  height: 30px;
  width: 500px;
  text-align: center;
  margin: 10px;
  position: relative; /* should be relative */
}
<p class='box'>This is centered</p>

<p class='box'>This is not<span class='circle'></span></p>

要使文本垂直和水平居中:

.circle {
  height: 20px;
  width: 20px;
  background-color: blue;
  border-radius: 50%;
  display: inline-block;
  /* added */
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 10px;
}

.box {
  background-color: yellow;
  height: 30px;
  width: 500px;
  text-align: center;
  margin: 10px;
  position: relative; /* should be relative */
  
  /* add these to center text vertically and horizontally */
  display:flex;
  align-items:center;
  justify-content: center;
}
<p class='box'>This is centered</p>

<p class='box'>This is not<span class='circle'></span></p>


好的,谢谢!“transform: translateY(-50%)”是什么意思?这只是将蓝色圆圈移到最右边吗? - SNN
1
top: 50%transform: translateY(-50%) 是将其垂直居中的必要样式。 - doğukan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接