首页 > 解决方案 > 将元素对齐到其向左浮动的父元素的右侧

问题描述

我想要一些左浮动元素上方的工具提示。我想要一些工具提示左对齐到他们兄弟的左边距,一些右对齐到他们工具提示的右边距。我不知道如何让元素相对于左浮动的兄弟元素右对齐。

下面是我尝试过的代码。我试图让绿色和蓝色段上的工具提示与彩色段的右侧而不是左侧对齐,但它不起作用。

.textContent {
  margin: 5px  0;
}
.bar {
	box-sizing: border-box;
	cursor: default;
	height: 10px;
  overflow: visible;
	width: 100%;
}
.segment {
	cursor: pointer;
	display: inline-block;
	float: left;
  height: inherit;
	position: relative;
  width: 20%;
}
.section1 {
  background-color: red;
}
.section2 {
  background-color: orange;
}
.section3 {
  background-color: yellow;
}
.section4 {
  background-color: green;
}
.section5 {
  background-color: blue;
}
.segment .tooltip {
	background-color: #ffffff;
	border: 1px solid #cc0000;
	border-radius: 5px;
	color: #000000;
	float: left;
	margin-top: 15px;
	padding: 5px;
	position: absolute;
	text-align: center;
	visibility: hidden;
	z-index: 1;
}
.alignRightTooltip {
  float: right;
}
.segment:hover .tooltip {
  visibility: visible;
}
<DIV class="textContent">
  Hover over bar to display tooltips
</DIV>
<DIV class="textContent">
  The tooltips on the <SPAN style="color: green; font-weight: bold">green</SPAN> and <SPAN style="color: blue; font-weight: bold">blue</SPAN> bars should align to the right hand side of the segments
</DIV>
<DIV class="bar">
  <DIV class="segment section1">
    <SPAN class="tooltip">
      section1
    </SPAN>
  </DIV>
  <DIV class="segment section2">
    <SPAN class="tooltip">
      section2
    </SPAN>
  </DIV>
  <DIV class="segment section3">
    <SPAN class="tooltip">
      section3
    </SPAN>
  </DIV>
  <DIV class="segment section4">
    <SPAN class="tooltip alignRightTooltip">
      section4
    </SPAN>
  </DIV>
  <DIV class="segment section5">
    <SPAN class="tooltip alignRightTooltip">
      section5
    </SPAN>
  </DIV>
</DIV>

我会很感激任何反馈,不确定我做错了什么。

谢谢!

标签: csscss-floatcss-position

解决方案


请尝试此代码..如果您想要工具提示的右对齐,请添加“右对齐”类..

HTML

<DIV class="segment section4 right-align">
  <SPAN class="tooltip alignRightTooltip">
    section4
  </SPAN>
</DIV>
<DIV class="segment section5 right-align">
  <SPAN class="tooltip alignRightTooltip">
    section5
  </SPAN>
</DIV>

CSS

.segment.right-align span {
  right: 0;
}

推荐阅读