问题描述:

I have a div with unknown height, though in this example I'm using 3px. I want to center the button but it seems to always offset by some arbitrary amount. I could do an absolute positioning trick dynamically once I know the height but I would prefer a css solution if possible.

<div style="width: 100%; height: 3px;">

<div class="special">

<input type="button" />

</div>

</div>

div{

height: 100%;

overflow: visible;

}

.special{

position:relative;

text-align: center;

padding: 1px;

border: 1px solid red;

}

input{

height: 100%;

width: 100px;

min-height: 8px;

}

The idea is that with the min-height the button will overflow evenly over the top and bottom of the div.

jsfiddle

网友答案:

You can get this to work by doing the following:

CSS:

div {
    height: 100%;
    overflow: visible;
}
.special {
    text-align: center;
    border: 1px solid red;
    position:relative;
}
input {
    position:absolute;
    margin-top:-4px;
    margin-bottom:-4px;
    top:0px;
    bottom:0px;
    width:100px;
    min-height:7px;
}

Note the input declaration in particular. Instead of height:100% I used position:absolute with top:0px and bottom:0px. This will set the height to 100%. It needs to be position of absolute so that you can do margin-top:-4px and margin-bottom:-4px to get the overlap. You can see that it works for any height of the outer <div/>.

The JSFiddle below has some added controls so you can change the height of the .special <div/> without needing to refresh.

http://jsfiddle.net/bmyAW/8/

相关阅读:
Top