vandelay vandelay - 1 month ago 10
CSS Question

css, absolute positioning elements within relative positioning elements cluttering up

I'm trying to position my elements with absolute positioning within my relative div element. But it's cluttering up on eachother, as shown in this picture:

enter image description here

Probably not the best picture. But there's two identical divs on top of eachother.

I wanted the second copy of place itself under the first one, and so on if there were more. And thought relative was the way to do it. But it seems like I'm getting complications of the divs inside the relative container, if they have absolute positioning?

<div class="industryoutter">
<div class ="industryinnerleft">
Agricultural Chemicals
</div>
<div class ="industryinnerright">
C
</div>
</div>
<div class="industryoutter">
<div class ="industryinnerleft">
Agricultural Chemicals
</div>
<div class ="industryinnerright">
C
</div>
</div>


css

.industryoutter {
position: relative;
background-color: #c0c0c0;
width: 210;
}

.industryinnerleft {
position: absolute;
left: 5px;
}

.industryinnerright {
position: absolute;
right: 5px;
}

Answer

Using absolute positioning for things like this is just bad practice, it makes everything harder. The easiest thing you could do is to just float .industryinnerright right, like:

.industryoutter {
  position: relative;
  background-color: #c0c0c0;
  width: 210px;
  overflow: hidden;
}
.industryinnerright {
  float: right
}
<div class="industryoutter">
  Agricultural Chemicals
  <span class="industryinnerright">C</span>
</div>
<div class="industryoutter">
  Agricultural Chemicals
  <span class="industryinnerright">C</span>
</div>

Make sure you add overflow: hidden; to .industryoutter so it will grow to fit its content's height. You also no longer need to wrap the left text in a div.

Comments