Center and right align flexbox elements with text-oveflow and taking empty space on left side

纵饮孤独 提交于 2021-02-16 22:45:58

问题


@michael-benjamin Center and right align flexbox elements almost what I want, but with 2 differences:

  1. Div have to take empty space at left side too (when it be wide)
  2. Div have to collapse text when there is no empty space around at all.

What I have?

A is main centered object and BBBBBBBBBBBBBBB is right object.

This is fine till A will grow:

What I want?

Is it possible to do with flex/grid/table-tr-td/any other css tricks?

What I tried?

  1. CSS Positioning Properties - can't stop when grow to B
  2. Flex Auto Margins & Invisible Flex Item (DOM element) - invisible item don't give empty space at left side
  3. CSS Grid Layout - 1fr don't give empty space at left side

回答1:


CSS grid can do it like below:

.container {
  margin: 10px;
  display: grid;
  grid-template-columns: 1fr minmax(0,max-content) 1fr;
  color: #fff;
}
.container::before {
  content:"";
}

.b {
  margin-left: auto;
  background: grey;
}

.a {
  margin: auto;
  background: blue;
  overflow:hidden;
  text-overflow:ellipsis;
  max-width:100%;
}



body {
  background:linear-gradient(red,red) center/ 2px 100% no-repeat;
}
<div class="container">
  <div class="a">AA</div>
  <div class="b">BBBBBBBBBBBBBBBB</div>
</div>

<div class="container">
  <div class="a">AA</div>
  <div class="b">BBBBBBBBBBBBBBBB</div>
</div>

<div class="container">
  <div class="a">AAAAAAAAAAAAAA</div>
  <div class="b">BBBBBBBBBBBBBBBB</div>
</div>

<div class="container">
  <div class="a">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</div>
  <div class="b">BBBBBBBBBBBBBBBB</div>
</div>

<div class="container">
  <div class="a">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</div>
  <div class="b">BBBBBBBBBBBBBBBB</div>
</div>


来源:https://stackoverflow.com/questions/62471264/center-and-right-align-flexbox-elements-with-text-oveflow-and-taking-empty-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!