如何在具有固定宽度的父div内进行固定位置子div包装

时间:2014-12-04 14:30:15

标签: html css

我试图在父div中包含一个固定位置的子元素,而不会破坏div。

我希望它的行为类似于未修复的div,但我需要修复子元素并自动换行或调整大小,因为我将需要它用于响应式站点。所以这就是为什么我真的不想做溢出情况,如果可能的话,因为我将在固定的div中拥有正确的对齐内容

HTML

<div class="parent">
   <div class="child">I am a child div with a 100% width</div>
</div>


<div class="parent">
   <div class="child-unfixed">I am a child div that is unfixed (this is the desired affect I am   after but using a fixed position if possible)</div>
</div>

CSS

.parent {
   background:green;
   padding:20px;
   margin-bottom:20px;
   margin-right:100px;
   width:200px
}

.child {
   background:yellow;
   position:fixed;
   width:100%;
   text-align:right;
}
.child-unfixed {
   background:pink;
}

Here is the JSfiddle

4 个答案:

答案 0 :(得分:1)

position: fixed;不能在div内。它粘在窗户上,不能粘在html元素上。

请参阅developer.mozilla.org

  

固定

     

不要为元素留出空间。相反,将其放置在相对于屏幕视口的指定位置,并且在滚动时不要移动它。打印时,将其放在每页的固定位置。

答案 1 :(得分:0)

http://jsfiddle.net/tLbggwp8/11/

尝试删除另一个答案中指示的position:fixed;,然后将max-width设置设置为父div和填充的差异。

手动我已将其设置为460px(每侧20px填充)。

您可以使用其他一些方法来帮助布局:

  • 使用calc [max-width:calc(x-y);]函数计算max-width以获得更多动态用途
  • box-sizing:border-box;协助确定区域的真实大小,并在最终的大小计算中包含填充和边距

答案 2 :(得分:0)

起初我认为没有办法做到这一点,因为它的作用就像一个绝对的div并占据了页面的元素。

但似乎继承宽度就行了。

width: inherit;

http://jsfiddle.net/susannalarsen/tLbggwp8/12/

答案 3 :(得分:0)

我遇到了这个问题,并认为我会为可能发现此问题的任何人添加适用于我的解决方案。而不是将子位置设置为固定,而是将父位置设置为固定,然后将子位置设置为绝对。

这是我使用的代码:https://codepen.io/redclaycreative/pen/MLeEee

HTML

<body>
  <div class="parent shadow">
    <h1 class="child">東京からこんにちは</h1>
  <div>
</body>

CSS

.parent {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 500px;
  max-width: 90%;
  height: 300px;
  background-color: #C6312D;
  -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

.child {
  display: inline-block;
  position: absolute;
  top: 50%;
  left: 50%;
  width: 300px;
  max-width: 90%;
  text-align: center;
  color: #fff;
  -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}