A Div中的绝对居中物品

时间:2015-07-25 22:15:28

标签: html css

我试图在div中居中(垂直和水平)项目。我在这里和其他地方环顾四周,似乎无法得到任何工作。我正在寻找的是让每个项目在其各自的div中垂直和水平居中。请注意,左侧有两个导航磁贴,右侧有4个导航磁贴(每个磁贴1个)。 div也有父div,我用它来构建粘性页脚。挑战在于它需要响应,所以我不能使用固定像素。

.absolute-center {
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
   }

以上就是我试图让内容居中的原因。不幸的是它没有工作。 这是小提琴:https://jsfiddle.net/jmc3t164/

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

你有这种结构(为简洁而缩短)

    <div class='top-half'>
        <p class='absolute-center'>Time left to order</p>
    </div>
    <div class='bottom-half'>
        <p class='absolute-center'>Add Produce</p>
    </div>

水平垂直居中通常由

实现
.absolute-center {
    position: absolute; /* note */
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

但这要求父元素(子项将居中于其中)具有position:relative

所以,你需要添加

.top-half {
    width: 100%;
    height: 50%;
    position: relative;
}
.bottom-half {
    width: 100%;
    height: 50%;
    position:relative;

}

JSFiddle Demo

答案 1 :(得分:-1)

<div id="blahblah" style="width:90%;margin:auto 5%"> content </div><br> blahblah can be any id you want, or not necessary.<br> You definitely need a width of something, ideally less than 100%; and divide the remainder from 100 by 2 and set it as margin. ( margin: auto is for up and down margings, the 5%, or whatever is for left / right.

另一种方法是使用.center {text-align:center}类并将其分配给你的Div。 最后,还有一个是在你的位置相关的div下插入一个div并用&text;对齐:中心来设置它。