Home > Software engineering >  centering div within div with uneven padding
centering div within div with uneven padding

Time:10-22

Here's the problem. I'm given a div with uneven top and bottom padding. There is a text box centered in the div. Like so: enter image description here

as the user adds more text, the text box will expand both up and down, until it hits the top padding (since the top is padded more). enter image description here

if the user adds more text, the text box will only expand downwards, until it hits the bottom padding. enter image description here

if the user continues adding text, the outer div will expand to accomodate. I have tried messing with padding in the outer div, but the text box will then center slightly lower in the div (to account for the extra padding on top). Any ideas on how to circumvent this? here is a jsfiddlewith some starter code.

CodePudding user response:

Maybe you can try to do this way let me know if this will work. I flex the text then wrap it. let me know.

.outer-wrapper {
  border: 1px solid black;
  min-height: 200px;
  width:500px;
  display: table;
  padding: 20px 10px 40px 10px
}

.inner-wrapper {
  display: table-cell;
  vertical-align: middle;
  border: 1px dotted black;
  font-size: 30px;
}

.inner-wrapper span {
  display: flex; 
  justify-content: center; 
  flex-wrap: wrap;
  text-align: center;
  padding: 10px;
  }
<div >
<div ><span>THIS IS A SAMPLE TEXT THAT NEEDS TO BE CENTER PLEASE CENTER ME</span></div>
</div>

CodePudding user response:

If you don't use borders for the inner wrapper, then you can add the missing padding to it whether top or bottom.

.outer-wrapper {
    border: 1px solid black;
    min-height: 200px;
    width:500px;
    display: table;
    padding: 40px 10px 20px 10px;
  }
  
  .inner-wrapper {
    display: table-cell;
    vertical-align: middle;
    /* border: 1px dotted black; */
    font-size: 30px;
    padding-bottom: 20px;
    text-align: center;
  }
<div >
    <div ><span>
      hello there hello there hello there hello there hello there hello there 
      hello there hello there hello there hello there hello there hello there 
      hello there hello there hello there hello there hello there hello there 
      hello there hello there hello there hello there hello there hello there 
      hello there hello there hello there hello there hello there hello there 
      hello there hello there hello there hello there hello there hello there 
    </span></div>
    </div>

  • Related