2013-05-02 58 views
1

不知道容器的高度是否可以居中垂直?不知道容器高度的垂直中心

我试过显示:内嵌块和垂直对齐:中间,它不起作用。我究竟做错了什么?

这里查看:http://jsfiddle.net/dSq2n/

HTML:

<div class="wrap"> 
    <div class="red1"></div> 
    <div class="red2"></div> 

    <div class="text"> 
     first<br> 
     second<br> 
     third<br> 
     forth 
    </div> 
</div> 

CSS:

.wrap{ 
    position:absolute; 
    top:10px; left:10px; 
    width:200px; 
    text-align:center; 
    background:grey; 
} 

.red1, .red2{ 
    position:absolute; 
    width:20px; height:20px; 
    display:inline-block; /* ? */ 
    vertical-align: middle; /* ? */ 
    background:red; 
} 

.red1{ 
    left:0px; 
} 
.red2{ 
    right:0px; top:0px; 
} 
+0

你如何使用'和'位置absolute'垂直align'? – 2013-05-02 11:16:43

回答

1

您使用position: absolute;所以使用vertical-align是没有用的,像这样做

Demo

.red1, .red2{ 
    position:absolute; 
    width:20px; height:20px; 
    background:red; 
    top: 50%; 
    margin-top: -10px; 
} 

你也需要从

删除 top: 0;
.red2{ 
    right:0px; 
} 

说明:我们在这里做的是使用top: 50%;将元素降低50%;但这并不是完全居中,所以我们-10px;使用margin-top这是要居中元素的总高度的1/2垂直

+0

你是赖特。谢谢。我有三个很好的答案,并在同一分钟。我不知道我必须选择哪一个女巫? – Nrc 2013-05-02 11:33:26

1

假设你要垂直居中的红色盒子,是的,这是可能的。但是你确实需要知道那些盒子的高度(你这样做)。只需使用以下属性:

top: 50%; 
margin-top: -10px; // half the height of the element 

演示:http://jsfiddle.net/dSq2n/2/

1

习惯了这种的CSS

.red1, .red2{ 
    position:absolute; 
    width:20px; height:20px; 
    top:50%;margin-top:-10px; 
    margin-top:-10px; 
    background:red; 
} 
.red1{left:0;} 
.red2{right:0;} 

删除display inline-block

Demo

+0

我有3个很好的答案,并在同一个确切的分钟。我不知道我必须选择哪一个女巫? – Nrc 2013-05-02 11:34:30

0

你不能使用position:absolute然后说vertical-align:middle

+0

我不明白你的答案。它已经是位置:绝对和垂直对齐:中间。你什么意思? – Nrc 2013-05-02 11:26:24

+0

你**不能** – Flowen 2013-05-02 11:28:17

1

这里的解决方案试试这个检查这个小提琴http://jsfiddle.net/sarfarazdesigner/dSq2n/6/

.red1, .red2{ 
    position:absolute; 
    width:20px; height:20px; 
    display:block; /* how you want to display */ 
    top:50%; /* give position from top */ 
    margin-top:-10px; /* put minus margin from top formula is total height/2 */ 
    background:red; 
} 

.red1{ 
    left:0px; 
} 
.red2{ 
    right:0px; 
}