-1

I have one html and css that I want to make sure children elements svg and 2 <p> elements centered both vertically and horizontally. I have tried align-items justify-content on my parent element it works. But it also change the other properties. so is it possible to set up the child element ONLY on child element css level

html file

<div class="container">
  <div class="box">
    <svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg> 
    <p>it should be center</p>
    <p>it should be center on vertical</p>
  </div>
</div>

css file

// center horizontally. styles on parent
.container {
  height: 500px;
  width: 700px;
  display: flex;
  border: 1px solid #000000;
}
.box {
  align-self: center;
  align-items: center;
  justify-content: center;
}

https://codepen.io/jacobcan/pen/WNpdWMV

jacobcan118
  • 7,797
  • 12
  • 50
  • 95
  • *But it also change the other properties* --> clarfiy this point – Temani Afif Jun 01 '21 at 21:11
  • my app is under react so the box only display under if condition. else it should display the other element `div class='second'`. I tried to place `align-items justify-content` at `container` level so in the else, it change element that belongs to `class=second` as well – jacobcan118 Jun 01 '21 at 22:19
  • so use margin:auto on the box element – Temani Afif Jun 01 '21 at 22:24
  • yap...i tried it as well...but it created a scrollbar vertically for some reason – jacobcan118 Jun 01 '21 at 23:05
  • it will do if your element is bigger than the container which is logical, otherwise you won't get any scrollbar – Temani Afif Jun 01 '21 at 23:10

1 Answers1

1

You need to put the justify/align on the parent.

.container {
  height: 100vh;
  display: flex;
  border: 1px solid #000000;
  align-items: center;
  justify-content: center;
  text-align: center
}
<div class="container">
  <div class="box">
    <svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg>
    <p>it should be center</p>
    <p>it should be center on vertical</p>
  </div>
</div>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161