2013-03-01 69 views
8

我的代码是这样的。如何向右对齐div内的固定位置div

<div class="outer"> 
    <div class="inner">some text here 
    </div> 
</div> 

CSS:

.outer { 
    max-width:1024px; 
    background-color:red; 
    margin:0 auto; 
} 
.inner { 
    width:50px; 
    border:1px solid white; 
    position:fixed; 
} 

它位于左默认内格需有w.r.t外格,而不是页面被定位。

如果我提到它是正确的:0px;它使它从浏览器中执行0px而不是外部div的右侧。

注意:我的外部div不是固定宽度。它根据屏幕分辨率进行调整。它的响应式网站设计。

+0

谢谢,我必须添加最大宽度与%宽度,但它使得完美的解决方案。 – 2013-03-01 10:38:22

回答

9

你可以使用一个div容器:

<div class="outer"> 
    <div class="floatcontainer"> 
     <div class="inner">some text here</div> 
    </div> 
</div> 

然后用它来处理float,和让其子女position: fixed

.outer { 
    width:50%; 
    height:600px; 
    background-color:red; 
    margin:0 auto; 
    position: relative; 
} 
.floatcontainer { 
    float: right; 
} 
.inner { 
    border:1px solid white; 
    position:fixed; 
} 
.floatcontainer, .inner{ 
    width: 50px; 
} 
7

你为什么不使用position:absolute

position:fixed总是相对于浏览器

.outer { 
    width:200px; 
    height:600px; 
    background-color:red; 
    margin:0 auto; 
    position:relative 
} 
.inner { 
    width:50px; 
    border:1px solid white; 
    position:absolute; right:0 
} 

DEMO


如果是强制使用position:fixed那么你可以指定margin-left值,因为你正在使用固定的两个div。

.inner { 
    width:50px; 
    border:1px solid white; 
    position:fixed; margin-left:150px 
} 

DEMO 2

+0

你的第二个解决方案似乎正在工作,但与我的外部div的问题不是固定的宽度。它根据屏幕宽度自行调整。所以我不能在里面声明宽度。我已经在我的查询中更新了 – 2013-03-01 10:12:03

+0

@RavishKumar使用位置时出现了什么问题:绝对 – Sowmya 2013-03-01 10:18:19

+0

我想要的是它应该从顶部和内部主体div中修正20%。 – 2013-03-01 10:20:24

2

两个选项。只需浮动内部权利,或者使用绝对定位来实现它。

对于浮动只需设置float:right在内部DIV和overflow:隐藏在外部DIV上。

对于绝对定位,只需设置位置:相对于外部DIV和设置位置:绝对和右:0顶部:0在内部DIV上。

+0

这些都不能用'position:fixed'工作,而且我不确定'overflow:hidden'会有什么帮助。 – 2013-03-01 09:59:19

+0

它使它与页面对齐而不是外部div – 2013-03-01 10:03:09

+0

@ Twon-ha - 添加overflow:隐藏到包含浮动子元素的父容器允许父容器的高度增长以包含浮动子元素。 – 2013-03-01 10:31:55

1

如果万一,你想使.inner元素作为一个固定的定位元素,离开内.outer其他的东西是“滚动”,我建议你设置.inner位置作为绝对定位的元素。然后,创建后,一个新的包装与overflow:auto

<div class="outer"> 
    <div class="inner">Some text here...</div> 
    <div class="flow">content</div> <!-- extra markup --> 
</div> 

这里有一个演示:http://jsfiddle.net/tovic/ZLbqn/3/

1

我认为这是你想要的

<div class="outer"> 
    <div class="inner">some text here 
    </div> 
</div> 


.outer { 
    margin: 0 auto; 
    width: 860px; 
    direction: rtl; 
    background-color: black; 
    height: 1200px; 
} 

.inner { 
    float: right; 
    position: fixed; 
    text-align: center; 
    width: 220px; 
    background-color: red; 
    height: 50px; 
}