简体   繁体   English

如何调整子元素的宽度而不调整CSS中父元素的宽度?

[英]How to adjust width of a child element without adjusting the width of the parent in CSS?

I have the following: 我有以下内容:

<div class="parent">
  <div class="sizer" />
  <div class="child" />
</div>

.sizer {
width: 200px;
}

.child {
position: relative;
width: 400px;
}

I am not allowed to explicitly set the width on the parent, and I am not allowed to set the child to position:absolute . 我不允许在父项上显式设置宽度,我不允许将子项设置为position:absolute

Using CSS, is there any other way to set the width of .child to 400 without also having the width of .parent expand from 200 to 400? 使用CSS,有没有其他方法可以将.child的宽度设置为400而不.parent的宽度从200扩展到400?

If the parent has a set width, then it will not expand with the width of the child, even if the child's width exceeds that of the parent. 如果父级具有设置的宽度,则它不会随子级的宽度扩展,即使子级的宽度超过父级的宽度也是如此。 See this JS Fiddle example . 看到这个JS小提琴示例

.parent {
    width: 300px;
    height: 50px;
}

.child {
    width: 400px;
    height: 50px;
    position: relative;

}

在此输入图像描述


UPDATE UPDATE

I am wondering if there is any kind of hack that allows me to do it without setting width on parent 我想知道是否有任何类型的黑客允许我这样做而不设置父级宽度

There is no way to accomplish this without the parent having some sort of width or width-like property. 如果没有父类具有某种宽度或类似宽度的属性,则无法实现此目的。 If you are only opposed to using the width property on the parent, you can use several width-like alternatives. 如果您只反对在父级上使用width属性,则可以使用多个类似宽度的替代方法。

As cimmanon explained in a comment below, you could set .parent to have a max-width . 正如cimmanon在下面的评论中解释的那样,您可以将.parent设置为具有max-width It does not necessarily have to be 100% ; 它不一定必须是100% ; any max-width will do, as long as it is less than the width of the child. 任何最大宽度都可以,只要它小于孩子的宽度。 See this JS Fiddle example , or check out this code: 请参阅此JS Fiddle示例 ,或查看此代码:

.parent {
    max-width: 200px;
} 

.child {
   width: 400px;
} 

Alternatively, you could use position:absolute and set the left and right properties. 或者,你可以使用position:absolute ,并设置leftright属性。 See this JS Fiddle example , or check out this code: 请参阅此JS Fiddle示例 ,或查看此代码:

.parent {
    position:absolute;
    left:0;
    right:0;
} 

But remember, these are only two of the many possible alternatives. 但请记住,这些只是众多可能的替代方案中的两个。 Hope this helps! 希望这可以帮助!

You could set the max-width of the parent to 100%. 您可以将父级的最大宽度设置为100%。

http://jsfiddle.net/aFdzy/ http://jsfiddle.net/aFdzy/

.parent {
    max-width: 100%;
}

.child {
    width: 400%;
}

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

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