sourcecode

측면 항목의 너비가 다를 때 중간 항목 중심을 유지합니다.

copyscript 2023. 9. 6. 22:13
반응형

측면 항목의 너비가 다를 때 중간 항목 중심을 유지합니다.

enter image description here

점이 상자 사이의 공간을 나타내는 다음 레이아웃을 상상해 보십시오.

[Left box]......[Center box]......[Right box]

오른쪽 상자를 제거하면 다음과 같이 센터 상자가 계속 중앙에 있는 것이 좋습니다.

[Left box]......[Center box].................

제가 왼쪽 박스를 제거할 경우에도 마찬가지입니다.

................[Center box].................

이제 센터 상자 내의 콘텐츠가 길어지면 중앙에 있는 콘텐츠는 필요한 만큼의 가용 공간을 차지하게 됩니다. 상자는 않을 것이고 있지 않을 쪽및는코지며서에때지을아이쪽때을e지아이let에doverflow:hidden그리고.text-overflow: ellipsis내용을 파기하기 위해 효력이 발생할 것입니다.

[Left box][Center boxxxxxxxxxxxxx][Right box]

위의 모든 것이 저의 이상적인 상황이지만, 이 효과를 어떻게 달성해야 할지 모르겠습니다.왜냐하면 이렇게 유연한 구조를 만들 때:

.parent {
    display : flex; // flex box
    justify-content : space-between; // horizontal alignment
    align-content   : center; // vertical alignment
}

왼쪽 상자와 오른쪽 상자의 크기가 정확히 같다면 원하는 효과를 얻을 수 있습니다.그러나 둘 중 하나의 크기가 다른 경우에는 중심 상자가 더 이상 중심에 있지 않습니다.

저를 도와줄 사람이 있습니까?

갱신하다

A justify-self좋을 것 같아요, 이상적일 것 같네요.

.leftBox {
     justify-self : flex-start;
}

.rightBox {
    justify-self : flex-end;
}

왼쪽 상자와 오른쪽 상자의 크기가 정확히 같다면 원하는 효과를 얻을 수 있습니다.그러나 둘 중 하나의 크기가 다른 경우에는 중심 상자가 더 이상 중심에 있지 않습니다.저를 도와줄 사람이 있습니까?

플렉스박스를 사용하여 형제의 폭에 상관없이 중간 항목의 중심을 잡는 방법이 있습니다.

주요 기능:

  • 순수 CSS
  • 절대 위치 없음
  • JS/jQuery 없음

auto여백:

.container {
  display: flex;
}
.box {
  flex: 1;
  display: flex;
  justify-content: center;
}

.box:first-child > span { margin-right: auto; }

.box:last-child  > span { margin-left: auto;  }

/* non-essential */
.box {
  align-items: center;
  border: 1px solid #ccc;
  background-color: lightgreen;
  height: 40px;
}
p {
  text-align: center;
  margin: 5px 0 0 0;
}
<div class="container">
  <div class="box"><span>short text</span></div>
  <div class="box"><span>centered text</span></div>
  <div class="box"><span>loooooooooooooooong text</span></div>
</div>
<p>&#8593;<br>true center</p>

작동 방식은 다음과 같습니다.

  • 디바( ().container 컨테이너 입니다는 플렉스 컨테이너 입니다.
  • 디브( ).box 아이템이 는 이제 플렉스 아이템이 되었습니다.
  • .box아이템을 드립니다.flex: 1컨테이너 공간을 균등하게 분배하기 위해 (상세한 사항).
  • 이제 항목은 행의 모든 공간을 사용하며 너비가 같습니다.
  • ① (②) ③ (③) ④ (④) ⑤ (⑤) ⑥ ⑦ justify-content: center.
  • 각각 ㅇㅇspan요소는 중심 플렉스 항목입니다.
  • 플렉스 사용auto을할백eot을sre span로 s

당신도 포기할 수 있습니다.justify-content을 합니다.auto 전용용

그렇지만justify-content여기서 일할 수 있는 이유는auto여백에는 항상 우선 순위가 있습니다.

8 8.1에 맞추어 하기 auto

에 을 을 justify-content그리고.align-self차원의 됩니다. 즉, 의 의 은 의 됩니다 에 됩니다 에 의 의 의

  1. 용기에 플렉스 아이템 3개 사용
  2. 세트 flex: 1처음과 마지막으로.이렇게 하면 중간에 남아 있는 사용 가능한 공간을 채우기 위해 동일하게 성장하게 됩니다.
  3. 따라서 가운데 쪽이 중심이 되는 경향이 있습니다.
  4. 첫 이 넓을 , 이나 를 으로 입니다 할 도 이 입니다 할 으로 이나 min-width: auto

    참고로 Chrome은 이것을 제대로 구현하지 않는 것 같습니다.그러나 설정할 수 있습니다.min-width-webkit-max-content아니면-webkit-min-content그것도 잘 될 겁니다.

  5. 이 경우에만 중간 요소가 중앙에서 밀려납니다.

.outer-wrapper {
  display: flex;
}
.item {
  background: lime;
  margin: 5px;
}
.left.inner-wrapper, .right.inner-wrapper {
  flex: 1;
  display: flex;
  min-width: -webkit-min-content; /* Workaround to Chrome bug */
}
.right.inner-wrapper {
  justify-content: flex-end;
}
.animate {
  animation: anim 5s infinite alternate;
}
@keyframes anim {
  from { min-width: 0 }
  to { min-width: 100vw; }
}
<div class="outer-wrapper">
  <div class="left inner-wrapper">
    <div class="item animate">Left</div>
  </div>
  <div class="center inner-wrapper">
    <div class="item">Center</div>
  </div>
  <div class="right inner-wrapper">
    <div class="item">Right</div>
  </div>
</div>
<!-- Analogous to above --> <div class="outer-wrapper"><div class="left inner-wrapper"><div class="item">Left</div></div><div class="center inner-wrapper"><div class="item animate">Center</div></div><div class="right inner-wrapper"><div class="item">Right</div></div></div><div class="outer-wrapper"><div class="left inner-wrapper"><div class="item">Left</div></div><div class="center inner-wrapper"><div class="item">Center</div></div><div class="right inner-wrapper"><div class="item animate">Right</div></div></div>

핵심은 사용하는 것입니다.flex-basis 솔루션은 다음과 같이 그렇다면 솔루션은 다음과 같이 간단합니다.

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

.left, .right {
   flex-grow: 1;
   flex-basis: 0;
}

코드펜은 여기서 사용 가능합니다.

여기 플렉스박스 대신 그리드를 사용하는 답변이 있습니다.이 솔루션은 승인된 답변처럼 HTML에 추가적인 손자 요소를 필요로 하지 않습니다.그리고 2019년의 그리드 답변과는 달리 한쪽의 콘텐츠가 중앙으로 넘칠 정도로 길어졌을 때도 올바르게 작동합니다.

질문에 설명된 것처럼 이 솔루션은 생략을 표시하거나 센터 상자에 추가 내용을 숨깁니다.

section {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
}

section > *:last-child {
  white-space: nowrap;
  text-align: right;
}

/* not essential; just for demo purposes */
section {
  background-color: #eee;
  font-family: helvetica, arial;
  font-size: 10pt;
  padding: 4px;
}

section > * {
  border: 1px solid #bbb;
  padding: 2px;
}
<section>
  <div>left</div>
  <div>center</div>
  <div>right side is longer</div>
</section>

<section>
  <div>left</div>
  <div>center</div>
  <div>right side is much, much longer</div>
</section>

<section>
  <div>left</div>
  <div>center</div>
  <div>right side is much, much longer, super long in fact</div>
</section>

기본적으로 플렉스박스를 사용하는 대신 그리드를 사용하면 상위 레벨의 자식 내부에서 추가 마크업 없이 CSS 2줄로 해결됩니다.

HTML:

<header class="header">
  <div class="left">variable content</div>
  <div class="middle">variable content</div>
  <div class="right">variable content which happens to be very long</div>
</header>

CSS:

.header {
  display: grid;
  grid-template-columns: [first] 20% auto [last] 20%;
}
.middle {
  /* use either */
  margin: 0 auto;
  /* or */
  text-align: center;
}

플렉스박스는 흔들리지만 모든 것에 대한 답이 되어서는 안됩니다.이 경우 그리드가 가장 깨끗한 옵션임이 분명합니다.

테스트의 즐거움을 위해 코드 펜도 만들었습니다. https://codepen.io/anon/pen/mooQOV

이렇게 할 수 있습니다.

.bar {
    display: flex;    
    background: #B0BEC5;
}
.l {
    width: 50%;
    flex-shrink: 1;
    display: flex;
}
.l-content {
    background: #9C27B0;
}
.m { 
    flex-shrink: 0;
}
.m-content {    
    text-align: center;
    background: #2196F3;
}
.r {
    width: 50%;
    flex-shrink: 1;
    display: flex;
    flex-direction: row-reverse;
}
.r-content { 
    background: #E91E63;
}
<div class="bar">
    <div class="l">
        <div class="l-content">This is really long content.  More content.  So much content.</div>
    </div>
    <div class="m">
        <div class="m-content">This will always be in the center.</div>
    </div>
    <div class="r">
        <div class="r-content">This is short.</div>
    </div>
</div>

또 으로 를 사용하는 방법이 .display: flex부모 및 자녀의 경우:

.Layout{
    display: flex;
    justify-content: center;
}
.Left{
    display: flex;
    justify-content: flex-start;
    width: 100%;
}
.Right{
    display: flex;
    justify-content: flex-end;
    width: 100%;
}
<div class = 'Layout'>
    <div class = 'Left'>I'm on the left</div>
    <div class = 'Mid'>Centered</div>
    <div class = 'Right'>I'm on the right</div>
</div>

저는 질문에 나온 정확한 결과를 원했고, 저는 가밀엘라와 에릭 마르틴 조단의 답변을 종합했고, 그것은 저에게 가장 적합합니다.

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

.left, .right {
   flex-grow: 1;
   flex-basis: 0;
}

.right {
   display: flex;
   justify-content: flex-end;
}

조금 더 강력한 그리드 솔루션은 다음과 같습니다.

.container {
  overflow: hidden;
  border-radius: 2px;
  padding: 4px;
  background: orange;
  display: grid;
  grid-template-columns: minmax(max-content, 1fr) auto minmax(max-content, 1fr);
}

.item > div {
  display: inline-block;
  padding: 6px;
  border-radius: 2px;
  background: teal;
}

.item:last-child > div {
  float: right;
}
<div class="container">
  <div class="item"><div contenteditable>edit the text to test the layout</div></div>
  <div class="item"><div contenteditable>just click me and</div></div>
  <div class="item"><div contenteditable>edit</div></div>
</div>

그리고 여기 Codepen: https://codepen.io/benshope2234/pen/qBmZJWN 에서 볼 수 있습니다.

enter image description here

중간 요소에 대한 정확한 중심 정렬에 도달하는 간단한 방법을 사용할 수도 있습니다.

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

.container .sibling {
    display: flex;
    align-items: center;
    height: 50px;
    background-color: gray;
}

.container .sibling:first-child {
    width: 50%;
    display: flex;
    justify-content: space-between;
}

.container .sibling:last-child {
    justify-content: flex-end;
    width: 50%;
    box-sizing: border-box;
    padding-left: 100px; /* .center's width divided by 2 */
}

.container .sibling:last-child .content {
    text-align: right;
}

.container .sibling .center {
    height: 100%;
    width: 200px;
    background-color: lightgreen;
    transform: translateX(50%);
}

codepen : https://codepen.io/ErAz7/pen/mdeBKLG

이 문제에 대해 제가 늦을지는 몰라도, 그 모든 해결책은 복잡해 보이고, 여러분이 직면한 경우에 따라 효과가 없을 수도 있습니다.

말하면,을 잡을 , 를 를 에 position : absolute, 다른 두 사람과 함께 있는 동안justify-content : space-between, 다음과 같이:

CSS:

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

.middle {
  position: absolute;
  margin-left: auto;
  margin-right: auto;
  /* You should adapt percentages here if you have a background ; else, left: 0 and right: 0 should do the trick */
  left: 40%;
  right: 40%;
  text-align: center;
}

/* non-essential, copied from @Brian Morearty answer */
.element {
  border: 1px solid #ccc;
  background-color: lightgreen;
}

p {
  margin: 5px;
  padding: 5px;
}
<div class="container">
  <p class="element">First block</p>
  <p class="middle element">Middle block</p>
  <p class="element">Third THICC blockkkkkkkkk</p>
</div>

Michael Benjamin은 적절한 대답을 했지만 더 이상 단순화할 수 없는 이유는 없습니다.

.container {
  display: flex;
}

.box {
  flex: 1;
  display: flex;
  justify-content: center;
}

.box:first-child { justify-content: left; }

.box:last-child  { justify-content: right;  }

그리고 html

<div class="container">
  <div class="box">short text</div>
  <div class="box">centered tex</div>
  <div class="box">loooooooooooooooong text</div>
</div>

언급URL : https://stackoverflow.com/questions/32378953/keep-the-middle-item-centered-when-side-items-have-different-widths

반응형