Home > Mobile >  CSS: How to overlap circle element properly
CSS: How to overlap circle element properly

Time:07-04

What I want to do is to cover circle element with square. But I can still see circle border.

When I inspect the element, the child element size doesn't include the parent's border (118px x 118px) so I tried to remove box-sizing: border-box;. Even though child element size is 120px x 120px, the same thing still happens.

How can I cover the circle properly?

.circle {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 1px solid red;
  box-sizing: border-box;
  background-color: white;
}

.square {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: white;
}

/* added by editor for betetr visualization purpose */
body {
  background: gray;
}
<div >
  <div ></div>
</div>

CodePudding user response:

The content itself starts within the border, not at the end of the border. As such you have to position the element out of the content area. Instead of using top, right, bottom, left you could simply use inset:

.circle {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 1px solid red;
  box-sizing: border-box;
  background-color: white;
}

.square {
  position: absolute;
  inset: -1px;
  background-color: white;
}

/* added by editor for betetr visualization purpose */
body {
  background: gray;
}
<div >
  <div ></div>
</div>

CodePudding user response:

You can cover the circle properly by adding a border also to the square. and moving it a bit.

.circle {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 1px solid red;
  box-sizing: border-box;
  background-color: white;
}

.square {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  height: 100%;
  background-color: rgba(255,255,255,0.5);
  border: 1px solid white;
}

/* added by editor for betetr visualization purpose */
body {
  background: gray;
}
<div >
  <div ></div>
</div>

  • Related