提问者:小点点

是否可以只使用CSS,以相同的宽度和高度刻字一个孩子,而不超过其父代?


我的想法是让子对象(@example the“.moon”)的高度和宽度相等,并且不超过父对象(@example the“.sun”)的宽度或高度。

因此,当父项宽度大于其高度时,子项的宽度和高度值为较小的值,即父项高度。

同样,当父代高度大于宽度时,孩子的宽度和高度值是较小的值,即父代宽度。

我的意思是在容器内刻录一个对象,但只使用CSS。

“填充顶部”技巧仅在父宽度大于高度时有效。我想“对象匹配”只适用于图像。

我确实引用了这些圆,只是为了清楚地表明边必须具有相同的值(高度和宽度),并且子元素可以包含元素。

我知道它可以完美地完成与JavaScript得到父高度和宽度,比较较小的一个,并将其设置为子高度和宽度,我用jQuery,但想知道它是否可能实现它没有jQuery或JavaScript,纯CSS。

试试这个例子并调整屏幕大小。

var pw = ""; var ph = ""; var cw = ""; var ch = "";

$( window ).resize(function() { 
  
pw = $('.sun').width();
ph = $('.sun').height();
cw = $('.moon').width();
ch = $('.moon').height();
  if(pw > ph){
  $('.moon').css({
      'width': ph + 'px',
      'height': ph + 'px'
  });
  }
  else {
  $('.moon').css({
      'width': pw + 'px',
      'height': pw + 'px'
  });
  }
});

function mySUNction() {
   
pw = $('.sun').width();
ph = $('.sun').height();
cw = $('.moon').width();
ch = $('.moon').height();
  if(pw > ph){
  $('.moon').css({
      'width': ph + 'px',
      'height': ph + 'px'
  });
  }
  else {
  $('.moon').css({
      'width': pw + 'px',
      'height': pw + 'px'
  });
  }
}
* {
  padding: 0;
  margin:0;
}
.sky {
  position: absolute;
  width: 100%;
  height: 100%;
  background: purple;
  display: flex;
  justify-content: center;
  align-items: center;
}
.sun {
  position: relative;
  width: 33%;
  /*padding-top: 33%;*/
  height: 33%;
  background: yellow;  
  display: flex;
  justify-content: center;
  align-items: center;
}
.moon {
  background: blue;  
  /*object-fit: fill;*/
  /*border-radius: 50%;*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="sky">
<div class="sun">
<div class="moon"></div>
</div>
<div>
<button onclick="mySUNction()">Click me</button>

共2个答案

匿名用户

如果你只想要视觉效果,可以使用渐变:

body {
  margin:0;
}
.sky {
  height: 100vh;
  background: purple;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sun {
  position: relative;
  width: 33%;
  height: 33%;
  background: 
   radial-gradient(circle closest-side,blue 99%,transparent 100%)
   yellow;
}
<div class="sky">
  <div class="sun">
  </div>
</div>

匿名用户

您可以使用33vh(它应该与.sun的高度匹配)作为子宽度。参见CSS以了解。月亮元素。

* {
  padding: 0;
  margin:0;
}
.sky {
  position: absolute;
  width: 100%;
  height: 100%;
  background: purple;
  display: flex;
  justify-content: center;
  align-items: center;
}
.sun {
  position: relative;
  width: 33%;
  /*padding-top: 33%;*/
  height: 33%;
  background: yellow;  
  display: flex;
  justify-content: center;
  align-items: center;
}
.moon {
  background: blue;  
  /*object-fit: fill;*/
  border-radius: 50%;
  height:min(33vh, 33vw);
  width: min(33vh, 33vw);
}
<div class="sky">
  <div class="sun">
    <div class="moon"></div>
  </div>
</div>