简体   繁体   中英

How to align button by vertically in div using JQuery/CSS?

There is the following code:

HTML:

<table>
    <tr>
        <td class="first_column">Sign in</td>
        <td class="second_column">->(1)</td>
        <td class="third_column"><div class="translated">Some text</div></td>
    </tr>
</table>

JS:

$(".translated").mouseenter(function(){
    if ($(this).hasClass("editable")){
        return;
    }
    var h=$(this).height();
    var w=$(this).width();
    $(this).empty();
    var field = $("<input/>", {
            type: "text",
            value:$(this).text()
        }).appendTo(this);
    var button = $("<button></button>").appendTo(this);
    field.height(h - field.outerHeight()+field.height());
    button.height(h-button.outerHeight()+button.height());
    $(this).height(h);
    $(this).width(w);
    $(this).addClass("editable");
});

CSS:

.translated
{
    color:green;
    font-weight:bold;
    vertical-align:middle;
    width:100%;
}

This code addes input and button items to div container when mouse focuses the div. But there is the following problem - button has got a good height, but incorrect align. I need that a new button item is in center of row by vertically. Please, tell me, how can I do it?

You have to set button width in your js code:

button.css('width', field.width());

try on this fiddle: http://jsfiddle.net/velthune/NCrUu/5/

I cleaned up your code, added a table row and set the width of input and button. They are different because of the margins and paddings browsers give these elements

http://jsfiddle.net/andreaslyngstad/BFwU7/

HTML

<table>
            <tr>
                <td class="first_column">Sign in</td>
                <td class="second_column">->(1)</td>
                <td class="third_column">
                  <div class="translated">Some text</div>
                </td>
            </tr>
<tr>
                <td class="first_column"></td>
                <td class="second_column"></td>
                <td class="third_column" id="button_container"></td>
            </tr>
 </table>​​​

CSS

table{
    width:100%
}
button{
    width:100px
}
input{
    width:96px
}
.translated {
    color:green;
    font-weight:bold;
    vertical-align:middle;
    width:100%;
  }​

JS

var field = $("<input/>", {
    type: "text",
    value: $(this).text()
})
var button = $("<button>sign in</button>")

$(".translated").mouseenter(function() {
    $(this).empty();
    field.appendTo(this);
    button.appendTo($("#button_container"));
});​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM