center vertical without knowing the height of the container

Is it possible to center vertical without knowing the height of the container?

I tried display:inline-block and vertical align: middle and it does not work. What am I doing wrong?

Here to check: 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;
}

Answers


You are using position: absolute; so using vertical-align is of no use, do it like this

Demo

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

Also you need to remove top: 0; from

.red2{
    right:0px;
}

Explanation : What we are doing here is, using top: 50%; to bring the element down by 50%; but this is not perfectly centered, so we subtract -10px; using margin-top which is 1/2 of the total height of the element you want to center vertically


Assuming you want to vertically center the red boxes, yes, it is possible. But you do need to know the height of those boxes (which you do). Just use the following properties:

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

demo: http://jsfiddle.net/dSq2n/2/


Used to this 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;}

Remove display inline-block

Demo


here is solution try this check this fiddle 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;
}

Need Your Help

MultiException and PerseistenceException in javaEE with Beans

jsp javabeans glassfish-4 java-ee-7 netbeans-8

I know there are a lot of threads to this topic, but after searching for ~10 hours without a solution I will ask in a new thread.

Array Initialization ways

c# linq

I know we can initialize an array

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.