将DIV集中在集中式DIV之上的最佳做法?

时间:2014-09-20 19:38:37

标签: html css

我有一个想要出现在屏幕中间的图像。 在它上面我希望有一个简短的文字,我想要在该图像上方的中心。

我已设法做到这一点"手动"左边距为负,但是有更好的方法吗?

此外,代码是否正常?

HTML:

<div class="central">
<div class="msg">This Message needs to be in the center</div>
<img src="image.gif" width="130" height="15" />
</div>

CSS:

<style>
.central {
    position: absolute;
    top: 35%;
    left: 50%;
    margin-left: -(X/2)px;
    margin-top: -(Y/2)px;
}
.msg {
    text-align:center;
    font-family:Arial;
    font-size:14px;
    color:#03C;
    margin-bottom:10px;
    margin-left:-70px;
}
</style>

4 个答案:

答案 0 :(得分:2)

我认为你可以这样做:

.msg {
   text-align:center;
   font-family:Arial;
   font-size:14px;
   color:#03C;
}

img {
   display: block;
   margin: 0 auto;
}

.central{
    margin-top: 50%;
}

答案 1 :(得分:1)

您可以尝试使用保证金 - 50%也是:

img {
   display: block;
   margin: 0 auto;
}

.central{
    margin-bottom: -50%;
}

答案 2 :(得分:0)

试试这个

HTML

<div class="central">
<div class="msg">This Message needs to be in the center</div>
<img src="image.gif"  />
</div>

CSS

.central img{
     display:block;
     width: 130px;
     height:15px;
     position:relative;
     margin:0 auto;
}

答案 3 :(得分:0)

试试这个:

HTML:

<div class="central">
    <div class="msg">This Message needs to be in the center</div>
    <img src="http://freedomdefined.org/upload/thumb/5/5c/Fd_sq_icon_sc.svg/64px-Fd_sq_icon_sc.svg.png" />
</div>

CSS:

.central {
    text-align:center;
    margin-top:'x' px; //such that it is vertically in the middle
 }

DEMO