0

I have a div that has two child elements. A span and a div which contain's an X. My goal is to right align the X.

https://jsfiddle.net/Le8hn0am/

enter image description here

What it should look like

enter image description here

I've tried suggestions from How to right align a hyperlink in a <div>? and How to align 3 divs (left/center/right) inside another div? but haven't had any luck

What I've tried

- float:right;
- margin-left: auto;

Any tips or suggestions would be greatly appreciated

Master
  • 2,038
  • 2
  • 27
  • 77
  • There is a lot of CSS here which rather obscures what it actually wanted. Do you need it all? – A Haworth May 13 '21 at 07:16
  • 1
    [How to align 3 divs (left/center/right) inside another div?](https://stackoverflow.com/questions/2603700/how-to-align-3-divs-left-center-right-inside-another-div) is 11 years old ! 3years old for the first link. Forget about float (at least for layouts) Use display: flex or display: grid. In your case grid would be my first choice – Cedric Cholley May 13 '21 at 07:25
  • @CedricCholley the age of a question doesn't matter. That 11 years old question is and will remain valid in 11 years from now – Temani Afif May 13 '21 at 08:02
  • @TemaniAfif In some cases questions could remain valid for 11 years and more, you are right. This is not one of the cases, CSS has changed a lot in the past... way less than 11 years. Now a days using `float` to create layout should be avoid, there are (much much much) better ways: `flex`and `grid` – Cedric Cholley May 13 '21 at 08:08
  • @CedricCholley I invite you to read that question then (it seems you didn't) – Temani Afif May 13 '21 at 08:10

3 Answers3

2

There is too much CSS to style such a simple object. In any case ...

  1. Add position:relative; to #DIV_1 {
  2. Add position: absolute; and right: 7px; to #DIV_3 {

Your fiddle with my changes

Baro
  • 5,300
  • 2
  • 17
  • 39
1

What could be done is to use display: grid on the parent (div) with 2 columns. the 1st column is set to auto and the 2nd to 1fr to use all the remaining space. Align column content to right (justify-items: end) and Voilà ;-)

/* new CSS code */
div {
  display: grid;
  grid-template-columns: auto 1fr;
  justify-items: end;
}

/* simplified code from your original fiddle  */
div {
  border-radius: 6px;
  box-sizing: border-box;
  height: 16px;
  width: 67.5781px;
  background-color: rgb(179, 229, 255);
  font: 600 12px / 12px "Source Sans Pro", Helvetica, Arial, sans-serif;
  padding: 2px 6px;
}


span {
  color: rgb(15, 27, 49);
}

a {
  color: rgb(0, 85, 139);
}
<div>
    <span>days</span>
  <a>X</a>
</div>

PS I've simplified the original code.

Cedric Cholley
  • 1,956
  • 2
  • 9
  • 15
0

You could just simply add the display flex property to the DIV and reduce the padding-left so that the x is always at the end of the div:

  display: flex;
  flex-direction: row;
  justify-content: space-between;

Fiddle

Andres Paul
  • 1,020
  • 16
  • 18