lk1234
lk1234

Reputation: 113

Vertically align a div with fixed positioning

I am new to stackoverflow and have searched through some of the other answers and tried a lot of different things but can't seem to get it right.

I need to vertically align the 'Hide Message' button with the paragraph of text so that the button appears in the centered alongside the text (jsFiddle link below). The button also needs to align with another div on the page so it has to have:

position: fixed;
right: 50px;

The main problem I am having with some of the other solutions is that if you shrink the browser, it doesn't stay vertically aligned with the text:

http://jsfiddle.net/d3R6v/2/

Upvotes: 1

Views: 1160

Answers (1)

Mr. Alien
Mr. Alien

Reputation: 157414

I don't think position: fixed; is a way to go here, instead of using fixed you should be using absolute but before that assign position: relative; to the parent element and modify your #hideMessage as

#hideMessage {
    display: inline-block;
    padding: 5px 10px;
    background-color: #555;
    color: #fff;
    cursor: pointer;
    position: absolute;
    right: 50px;
    top: 50%;
    margin-top: -15px; /* Negate 1/2 the total height of the button, 
                          this value currently is approx */
}

Demo

The reason I insisted position: absolute; is because that it will align related to the parent element whereas using fixed is relative to the viewport.

For more information over positioning, you can refer my answer here


If you have dynamic text

Coming to more cleaner solution, it would be better if you use display: table; for the parent element, and display: table-cell; for the child elements, and for the parent element of the button i.e now display: table-cell;, you can use vertical-align: middle; to vertically align the button to the dynamic text on the left hand side and also on resize, the button won't overlap the text.

Demo 2

#parent {
    background-color: #bbb;
    color: #fff;
    width: 100%;
    padding: 10px;
    display: table;
}
#text {
    width: 80%;
    display: table-cell;
}
#hideMessage {
    display: table-cell;
    color: #fff;
    cursor: pointer;
    vertical-align: middle;
    text-align: center;
}

#hello {
    background-color: #555;
    padding: 5px 10px;
    white-space: nowrap; /* Add if you want to prevent the 
                            button to wrap on resize */
}

Upvotes: 1

Related Questions