1

Right now I have

<p style="text-align: center">Hello world</p>
<p style="text-align: right">Hello world</p>

which gives me

                     Hello world
                                             Hello world

I'd like them to be on the same line. I've tried using float such as

<div style="float: left">This is on the left </div><div style="float: right">This is on the right</div>

But they both end up on the left on top of each other

This is on the left
This is on the right

Is there a way to get them aligned where I want on the same line?

doğukan
  • 23,073
  • 13
  • 57
  • 69
Damien Scott
  • 47
  • 1
  • 4

4 Answers4

2

@dgknca you can use flex

.container {
  display: flex; 
  justify-content: flex-end;
}
.item-center {
  margin: auto;
}
<div class="container">
  <div class="item-center">Item center</div>
  <div>Item right</div>
</div>
Alex Quintero
  • 1,160
  • 10
  • 21
1

You can use CSS Grid to divide a parent element evenly into columns and then flow content into each grid cell.

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}
.center {
  text-align: center;
}
.right {
  text-align: right;
}
<div class='grid'>
  <p class='left'>This is on the left </p>
  <p class='center'>This is in the center</p>
  <p class='right'>This is on the right</p>
</div>
Sean
  • 6,873
  • 4
  • 21
  • 46
0

Following your first example, you have "center" and "right" so I'm inferring from that what you want, the rest of OP isn't quite clear to me.

The tricky part is actually having one be perfectly center, and one be on the right, and nothing on the left. Usually for stuff like this I'd use flexbox and put an extra container on the left to get the centering to work.

Here it is - just have your container be flex. Then set items to grow using 0 as basis (this is important so content width does not shift the centering and you get 3 equal width containers regardless of content). Then just wrap the one you want on the right in another div and justify-content: flex-end to get it on the right.

That's the best I know off the top - maybe some better ways...

body { display: flex; }

body div { display: flex; flex: 1 1 0 }

body .f-right { justify-content: flex-end }


/* center line/decoration */
.center-line {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  height: 100%;
  width: 1px;
  background: blue;
  opacity: .3
}

body { margin: 0 }
<div></div>

<p>Hai from center</p>

<div class="f-right">
  <p>Hai from right</p>
</div>

<!-- just showing center -->
<div class="center-line"></div>
MrRobboto
  • 722
  • 3
  • 10
-1

For this to work you have to put them both in the same p element. Using two separate p elements will cause them to be on different lines. The example code you gave works because both the left and right side are in the same block element. Separating them into two block elements will cause them to stack on each other.

ms217
  • 40
  • 6