skip to Main Content

Trying to show the image center of the div using text-align: center; But not working. Also i have tried using

display: flex; justify-content: center;

But not working. How to resolve this issue?

app.component.html:

    <div class="box">
    <div class="grid1">
    <div class="grid2">
      <img src="https://assets.stickpng.com/thumbs/585e4d1ccb11b227491c339b.png" height="24" width="24"/>
    </div>
    <div class="grid3">Content</div>
    </div>
    </div>

app.component.css:

.box {
  position: relative;
  clear: both;
  padding: 13px;
  background-color: #fff;
  border-radius: 0px 8px 8px 8px;
  height: 100%;
  min-height: 25px;
}

.grid1 {
  display: grid;
  grid-template-columns: auto 1fr;
  grid-gap: 0px;
  border: 1px solid black;
  min-width: 97.5px;
  height: auto;
  margin-left: 12px;
  float: left;
}

.grid2 {
  margin: 3px 1px 1px 1px;
  border: 1px solid red;
  height: 24px;
  font-size: 7px;
  width: 23.4px;
  float: left;
  min-height: 62px;
  /* display: flex;
  justify-content: center;
  text-align: center; */
}

.grid3 {
  margin: 3px 1px 1px 1px;
  border: 1px solid red;
  height: 62px;
  font-size: 7px;
  min-width: 64.35px;
  float: left;
}

Demo: https://stackblitz.com/edit/angular-ivy-uy4bgp?file=src%2Fapp%2Fapp.component.css

2

Answers


  1. Use the the display: flex approach since it’s generally better for centering both horizontally and vertically. You should apply the display: flex property to the .grid2 div and remove any unnecessary float properties. Here’s how you can modify your CSS:

    .grid2 {
      display: flex;
      justify-content: center;
      align-items: center; /* This centers vertically as well */
      border: 1px solid red;
      height: 24px;
      font-size: 7px;
      width: 23.4px;
      /* float: left; Remove this line */
      min-height: 62px;
    }
    

    By adding display: flex to .grid2, the justify-content: center centers the content horizontally, and align-items: center centers it vertically within the div.

    Login or Signup to reply.
  2. .img {
      width: 300px;
    }
    
    .content {
      border: 1px solid;
      padding: 15px;
      display: flex;
      justify-content: center;
    }
    
    <div class="content">
      <img class="img" src="https://w0.peakpx.com/wallpaper/424/814/HD-wallpaper-nature-nature.jpg" alt="nature images">
    </div>
    

    use flex, the image will show centering both horizontally and vertically. please try this

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search