most venerable sir
most venerable sir

Reputation: 669

How do I make a child''s distances from left and top boundary of its parent equal?

enter image description here

The magnifying glass is a font awesome icon. Its parent box is the column space. I used justify-content: center and display: flex on the parent box to horizontally center the magnifying glass. But how do I make the magnifying distance from the top the same as its distance from the left or the right boundary of the parent box. So it looks like located at the center of a invisible square.

Upvotes: 0

Views: 38

Answers (1)

Will Hamic
Will Hamic

Reputation: 692

Here is a way you could do it using padding. The divs represent the sidebar and the white square represents the icon. The main thing to pay attention to in this is this:

box-sizing: border-box;
padding:calc((10% - 40px) / 2);

The first line makes it so adding padding doesn't make the object larger. The second like sets the padding on all insides of the sidebar to (width of sidebar - width of icon)/2. This should center the icon correctly and adjust as values change due to zooming or window resizing.

div.container {
  background-color:lightblue;
  height:200px;
  display:inline-block;
}

div.square {
  width:40px;
  height:40px;
  background-color:white;
}

div.c1 {
  width:10%;
  box-sizing: border-box;
  padding:calc((10% - 40px) / 2);
}

div.c2 {
  width:15%;
  box-sizing: border-box;
  padding:calc((15% - 40px) / 2);
}

div.c3 {
  width:20%;
  box-sizing: border-box;
  padding:calc((20% - 40px) / 2);
}
<div class="container c1">
  <div class="square"></div>
</div>

<div class="container c2">
  <div class="square"></div>
</div>

<div class="container c3">
  <div class="square"></div>
</div>

Also in the future include some CSS or HTML showing what you have tried so far in an attempt to solve the problem.

Upvotes: 1

Related Questions