OferP
OferP

Reputation: 393

Css flex - one item on the right, the other centered on the left space

I'm new to css and even newer to flex. I couldn't find an answer, so I started a new one.. I have the following container and item:

  .container {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .item {
    color: rgb(51, 51, 51);
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

This way I get 2 items on both sides (one left and one right). I would like to know how to do the following:

  1. The left item, will be on the left as before. From the point it ends, to the point the container ends - I with the right element to be centered.
  2. The left item, will be on the left as before. The right item will be 10px left from the right end of the container.

Thanks!

Upvotes: 4

Views: 3602

Answers (1)

serraosays
serraosays

Reputation: 7869

The solution to this problem is using nested flexboxes. Get rid of the display: block; on .item - you can't mix flex and block display rules like that.

What you want to do is set up series of containers:

  • one top level flex container
  • two equally sized flex containers inside of the the top level container

Markup will look like this:

<main class="container">
  <section class="left-container">
    <div class="item"></div>
  </section>
  <section class="right-container">
    <div class="item"></div>
  </section>
</main>

In the CSS layer, you give the top-level .container flex and then justify-content: space-between which pushes the containers to the sides.

.container {
  display: flex;
  justify-content: space-between;
}

In the two nested containers, you need to make them both display: flex; as well. Now you can control the positioning of your .item elements like you want. align-items: center controls the vertical axis so .left-container gets only that positioning while the right container gets justify-content: center; to control the vertical alignment.

.left-container {
  background-color: darkgray;
  display: flex;
  align-items: center;
  height: 200px;
  width: 50%;
}

.right-container {
  background-color: lightgray;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  width: 50%;
}

Styling on the item is pretty simple - I just gave height and width for demo purposes. They aren't necessary. If you want to do precise tweaks, use margin on .item to push slightly from these standards.

.item {
  background-color: red;
  height: 100px;
  width: 100px;
}

enter image description here

Codepen: https://codepen.io/staypuftman/pen/PmLyNM

Upvotes: 3

Related Questions