Home > OS >  How to push an element to the left of a div and another element to the right of that same div?
How to push an element to the left of a div and another element to the right of that same div?

Time:05-21

Basically I have this long bar div and 2 pieces of text inside the innerHTML of that div.

How would I make one of the elements hug the left side of the div and one hug the right side?

I thought float:left; and float: right; would have worked but only one of them can work at a time.

Any tips are appreciated.

CodePudding user response:

You haven't shared any code, so it's hard to know what you've attempted so far..

You mention you've set the text via innerHTML, but if you're instead able to actually edit the markup itself, then this left/right text split can easily be achieved by using flexbox. Here, I've sepearted the items with the justify-content property:

.longDiv {
background: orange;
width: 300px;
display: flex;
justify-content: space-between;
}
<div >
  <p>left text</p>
  <p>right text</p>
</div>

CodePudding user response:

You can have multiple floats in one container. See this example. I generally make sure the floats are defined "first", before the other content of the container. The order of the elements does make a difference on how they render.

.long {
  width: 200px;
  height: 2em;
  
  text-align: center;
}
.box {
  border: solid thin black;
}
.left {
  float: left;
}
.right {
  float: right;
}
<div >
  <span >L</span>
  <span >R</span>

  Sample text.
</div>

  • Related