Home > other >  Div expanding on both sides vertically when width is unknown and using translate(-50%, -50%);
Div expanding on both sides vertically when width is unknown and using translate(-50%, -50%);

Time:05-27

https://codepen.io/codepen19871/pen/KKQZgwQ

Is there a way to fix this behavior? I want to make sure that the div expands downward and never upward when adding text. Because of this, I need to used fixed width, but if I use fixed width, I can't make the div responsive to the size of the content. Is there a way to fix this?

 .child {
    background-color: rgba(255,255,255, 1);
    min-width: 10%;
    max-width: 20%;
    top: 90px;
    left: 50%;
    position:absolute;
    z-index: 2;
    transform: translate(-50%, -50%);
    overflow-wrap: break-word;
  }

If I remove translate, it won't center. I also tried using other styling such as:

width: max-content;

But nothing works, there doesn't seem to be a solution that doesn't require javascript. If so, is there a way to make it work in React and make it behave like as though I used max-content?

I just need to center the div without the div expanding above, it's as simple as that.

CodePudding user response:

You should use flexbox if you want to center your div, I'm not exactly sure what you're attempting to do, but here is my interpretation. Also, there is not a ton of things you can do with JS that you can't do in pure css.

      .parent {
        width: 100%;
        height: 200px;
        background-color: #8ae6a2;
        display: flex;
        justify-content: center;
      }
      .child {
        flex: 1 1 20%;
        max-width: 20%;
        background-color: rgba(255,255,255, 1);
        overflow-wrap: break-word;
      }

Of course the div of class .child needs to be an actual child of your parent for this to work, unlike in your codepen...

CodePudding user response:

Move child div under parent div and set Top 50%

 

 .parent{
     width: 100%;
     height: 200px;
     background-color: #8ae6a2;
     position: relative;
    }      
    .child {
     background-color: rgba(255,255,255, 1);
     min-width: 10%;
     max-width: 20%;
     top: 50%;
     left: 50%;
     position:absolute;
     z-index: 2;
     transform: translate(-50%, -50%);
     overflow-wrap: break-word;
     }
<div >
  <div >
   234234234343434234324324343242342342343242343243423
  </div>
</div>

  • Related