0

I have a bootstrap icon on the top right of a div that I'd like to be inline with a horizontally centered <p>. However, if I use float:right, the text shifts ever so slightly.

Is it possible to accurately center the text while the icon stays on the right?

Sample code here: https://jsfiddle.net/x1Lvyu6t/3/

.box {
  border: 1px black solid;
  width: 50%;
}

.subbox {
  margin-left: auto;
  margin-right: auto;
  border: 1px black solid;
  text-align: center;
}

p {
  text-align: center;
  margin: 0;
}

i {
  float: right;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css">
<div class=box>
  <i class="bi bi-question-circle"></i>
  <p>
    hello
  </p>
  <div class=subbox>
    Content
    <br> Content
    <br> Content
  </div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
hoshijun
  • 27
  • 6
  • 1
    Floats are all manner of trouble. I would look at this: [Center one and right/left align other flexbox element](https://stackoverflow.com/questions/38948102/center-one-and-right-left-align-other-flexbox-element) Depending on your Bootstrap version you may have flexbox support classes. Also, don't style elements by type. You don't want all your paragraphs centered with zero margin. And Bootstrap has classes for margin and text alignment, so be sure to use those when you can. – isherwood Jan 19 '23 at 20:30

1 Answers1

1

Assuming you don't need it to flow you could try this:

.box {
  border: 1px black solid;
  width: 50%;
}

.subbox {
  margin-left: auto;
  margin-right: auto;
  border: 1px black solid;
  text-align: center;
}

p {
  text-align: center;
  margin: 0;
  position: relative;
}

i {
  position: absolute;
  right: 0px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css">

<div class=box>
  <p>
    hello
    <i class="bi bi-question-circle"></i>
  </p>
  <div class=subbox>
    Content
    <br> Content
    <br> Content
  </div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Owl Surojit
  • 173
  • 1
  • 10
  • FYI, the snippet creation tool adds body elements automatically. You create duplicates when you add them to the snippet. Also, the Tidy button is your friend. :) – isherwood Jan 19 '23 at 20:31