简体   繁体   English

如何创建一个圆形div,其中可点击区域仍然是正方形并且悬停效果减小了它的半径

[英]How to create a circle div where the clickable area is still square and the hover effect have reduce it's radius

So I did was the snippet I've attached but the problem is when hovering on square area and not in the circle area or in the corner it's jittering.所以我做了我附加的片段,但问题是当悬停在方形区域而不是在圆形区域或角落时它会抖动。 I need to somehow keep the square area as clickable.我需要以某种方式保持正方形区域可点击。 I'm wondering on how to approach this properly.我想知道如何正确处理这个问题。

 .container { background-color: orange; width: 150px; height: 150px; } .container:hover { border-radius: 50%; background-color: red; }
 <div class="container"> </div>

enter image description here在此处输入图像描述

You can use pseudo elements such as ::after or ::before .您可以使用伪元素,例如::after::before

Though they insert content at selected element, ::after inserts content after the selected element and ::before inserts content before the selected element.虽然它们在所选元素处插入内容,但::after所选元素之后插入内容, ::before所选元素之前插入内容。

content property generates the pseudo element. content属性生成伪元素。 If you do not set that property, it will be content: none;如果您不设置该属性,它将是content: none; by default and your pseudo element is not generated.默认情况下,不会生成您的伪元素。

 .container { background-color: orange; width: 150px; height: 150px; } .container::after { content: ""; position: absolute; height: inherit; width: inherit; background-color: red; opacity: 0; transition: all .15s linear; } .container:hover::after { opacity: 1; border-radius: 50%; }
 <div class="container"> </div>

You can use a before pseudo element to be the background, so leaving the actual element untouched on hover.您可以使用 before 伪元素作为背景,因此在悬停时保持实际元素不变。

The before pseudo element is given the same dimensions as the element but changes its background from orange to red on hover, and its radius changes to 50%. before 伪元素的尺寸与元素相同,但在悬停时其背景从橙色变为红色,其半径变为 50%。

To achieve the correct positioning and sizing of the before pseudo element you need to set the actual element to have a position, in this case the snippet sets it to relative, and the pseudo element is positioned absolute, behind the actual element:为了实现之前伪元素的正确定位和大小,您需要将实际元素设置为具有位置,在这种情况下,代码段将其设置为相对,伪元素定位为绝对,在实际元素后面:

 .container { width: 150px; height: 150px; position: relative; } .container::before { content: ''; background-color: orange; position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; } .container:hover::before { border-radius: 50%; background-color: red; }
 <div class="container"> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM