True Center Vertical and Horizontal CSS Div
This question already has an answer here:
That technique requires the element to have a fixed width and height. You are not setting the width and height. Based on your border and margins, to center it, the width would need to be 190 pixels and the height would need to be 90 pixels. Using line-height
and text-align
in combination with a fixed width and height makes the text and border centered. Try it.
CSS
.center{
position: fixed;
top: 50%;
left: 50%;
width: 190px;
height: 90px;
line-height: 90px;
text-align: center;
margin-top: -50px;
margin-left: -100px;
border:5px solid black;
}
You can do it with pure CSS:
html {
width: 100%;
height: 100%;
}
body {
min-width: 100%;
min-height: 100%;
}
div.centeredBlueBox {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 300px;
height: 200px;
background-color: blue;
}
It is important to give concrete (eg: 300px
) and not derived (like: auto
or 30%
) values for width
and height
.
<div style='position:absolute; left:50%; top:50%; margin-left:(-)width_of_your_element/2px; margin-top:(-)height_of_your_element/2px'>
例如
<!DOCTYPE html>
<html>
<body>
<div style='border:1px solid; width:200px; height:200px; position:absolute; left:50%; top:50%; margin-left:-100px; margin-top:-100px'>hallo</div>
</body>
</html>
链接地址: http://www.djcxy.com/p/41652.html
上一篇: 将<a>元素中的文字与CSS垂直对齐