-1

In css how to center a div in between a div without touch the property of parent div. Only change the property of Child Div... Like:

<div style="width: 200px; height: 200px; display: flex; background: #f00;">
  <div style="height: 50px; width: 50px; background: green;">
    <!-- Change the property of this div -->
  </div>
</div>

I don't want to need parent css change.. anything else what can you do...

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    HI @anurag-dhiman, do you have any HTML and CSS that you could show us? What have you tried? – Bodrov Sep 20 '19 at 17:02
  • Without a class on the parent `div` the best you can do is this selector `div > div { properties here }` That's basically saying, _any direct child of the parent div_ – disinfor Sep 20 '19 at 17:07
  • i would assume the usual `position:relative; top:50%; left:50%; transform:translate(-50%,-50%);` would work – Rainbow Sep 20 '19 at 17:12
  • @ZohirSalak Thankyou So Much Your Answer is Perfect for me... – Anurag Dhiman Sep 20 '19 at 17:24
  • @AnuragDhiman i didn't that you have `display:flex;` i suggest you use margin the it's shown in the answer below, which is more reliable in case of overflow – Rainbow Sep 21 '19 at 13:09

2 Answers2

1

Just add margin: auto; to your child div.

.parent {
width: 200px; 
height: 200px; 
display: flex; 
background: #f00;
}
.child {
height: 50px;
width: 50px; 
background: green;
margin: auto;
}
<div class="parent">
  <div class="child">
    <!-- Change the property of this div -->
  </div>
</div>
Evik Ghazarian
  • 1,803
  • 1
  • 9
  • 24
0

Why can't you put styles on the parent? Anyways:

.parent {
  display: block;
  width: 100px;
  height: 100px;
  background-color: red;
}

.child {
  display: block;
  width: 20px;
  height: 20px;
  margin: auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  background-color: green;
}
<div class="parent">
  <div class="child"></div>
</div>
StefanBob
  • 4,857
  • 2
  • 32
  • 38