【问题标题】:css: is it possible to move the child elements inside the parent element so that the parent element is automatically resizedcss:是否可以在父元素内移动子元素,以便父元素自动调整大小
【发布时间】:2021-04-10 18:52:31
【问题描述】:

您知道是否可以不通过在父块内移动子块来“手动”设置父块的确切大小(使用position: relative; left: xxx;transform: translate())?

我举了一个例子-你可以看到移动的块超出了父块的底部边框,没有到达父块的右边框

但我希望元素完全适合父块

我可以通过手动设置坐标和大小来完成,但是只能用css自动完成吗?

    * {
        box-sizing: border-box;
    }
    
    .group {
        display: inline-block;
        
        margin: 0;
        padding: 0;

        font-size: 0;
        
        border: 1px solid black;
    }
    
    .group div {
        font-size:  20px;
        display: inline-block;
    }
    
    .group div:not(.main) {
        width:  128px;
        height: 128px;
        
        border: 1px solid red;
        background: lime;
    }
    
    .main {
        transform: translate(-20px, 20px);
        
        width:  192px;
        height: 192px;
        
        border: 1px solid blue;
        background: orange;
<div class = 'group'>
    <div>1</div>
    <div>2</div>
    <div class = 'main'>3</div>
</div>

【问题讨论】:

  • 用边距移动它?
  • @Temani Afif,不,不,我需要父块的边界严格接触子块,没有任何间隙

标签: html css position css-position


【解决方案1】:

您只需要在父级的边缘补偿子级的translate,从而消除任何间隙。

注意:我冒昧地清理了代码,消除了不必要的值并使解决方案更加清晰。希望它对你有用。

编辑:此解决方案不需要float,这可能是个问题。此外,您可以使用position: relative 代替transform 没有任何问题。

div {
  display: table;
  outline: 1px solid black;
  /* same amount as the transform to compensate */
  margin-right: -20px;
  margin-bottom: 20px;
}

div > div {
  display: inline-block;
  width: 128px;
  height: 128px;
  background: lightgreen;
}

div > div:last-child {
  width: 192px;
  height: 192px;
  
/* use this and delete the transform if you like:
      position: relative;
      right: 20px;
      top: 20px;    
*/
  
  transform: translate(-20px, 20px);
  background: orange;
}
<div>
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

【讨论】:

    【解决方案2】:

    您可以通过将子 div 设置为浮动然后移动最后一个带边距来实现此目的。

    .group {
      display: inline-block;
      margin: 0;
      padding: 0;
      font-size: 0;
      border: 1px solid black;
    }
    
    .group div {
      font-size:  20px;
      display: inline-block;
    }
    
    .group div:not(.main) {
      width: 128px;
      height: 128px;
      float: left;
      border: 1px solid red;
      background: lime;
    }
    
    .main {
      margin-top: 20px;
      margin-left: -20px;
            
      width:  192px;
      height: 192px;
      float: left;
      border: 1px solid blue;
      background: orange;
    }
    <div class = 'group'>
        <div>1</div>
        <div>2</div>
        <div class = 'main'>3</div>
    </div>

    请注意,这只是针对您的确切问题的解决方案,这意味着它只适合右侧和底部。

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 2016-07-16
      • 2010-12-18
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      相关资源
      最近更新 更多