Home > Back-end >  CSS to have content on center and something on right of the div
CSS to have content on center and something on right of the div

Time:12-21

How can I have content on the center and an icon on the right of the div. This currently gives something like this:

enter image description here

But I want it to be like this:

enter image description here

Notice in the above 50% is in the center of div and pencil icon is on the right.

.w-100 {
  width: 100%;
}
<div >
  <p>{value}</p>
  <img src="https://via.placeholder.com/50" />
</div>

CodePudding user response:

You can use flexbox for this...

.w-100 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.img-icon {
  align-self: end;
}
<div >
  <p>{value}</p>
  <img class='img-icon' src="https://via.placeholder.com/50" />
</div>

CodePudding user response:

You can use display:flex on parent element and flex-grow: 1 on the element you want to stretch.

See the Snippet below:

.content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  border: 1px solid lightgray;
}

p {
  text-align:center;
  flex-grow: 1;
}
<div >
  <p>50%</p>
  <img src="https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/24/edit-icon.png" width="24" height="24" />
</div>

CodePudding user response:

You can do this 2 ways:

  • The standard flexbox approach. Use align-items: center to put the text in the middle but there's a gotcha in that if there are two items stacked on top of each other and the icon on the top one is 50 pixels wide and the next below one is 80 pixels wide then the center-aligned element may not be aligned on top of each other correctly.

  • To make sure your element is 100% placed in the middle, use 3 divs, with flex-grow: 1 to make 3 equally wide containers then use margins to position the child elements to the center or right.

Also have a look at a similar answer on stackoverflow

.container {
  display: flex;
  width: 100%;
}

.container>div {
  flex-grow: 1;
  display: flex;
}

.container>div:nth-child(2)>p {
  margin-inline: auto;
}

.container>div:last-child>img {
  margin-left: auto;
}
<div >
  <div></div>
  <div>
    <p>50%</p>
  </div>
  <div>
    <img src='https://placekitten.com/50/50' />
  </div>
</div>

CodePudding user response:

There are multiple ways you can do this such as give styles to your div display: flex. Also you can use align: right.

I would recommend to learn basic flexbox.

  • Related