我有一个div标签,宽度设置为800像素。当浏览器宽度大于800像素时,它不应该拉伸div,但应该将它带到页面的中间。


当前回答

父母{ 位置:相对; } 孩子{ 位置:绝对的; 左:50%; 变换:translateX (-50%); } <父> <孩子> 儿童> < / 父> < /

其他回答

Flexbox解决方案是2015年的发展方向。Justify-content: center用于父元素将内容对齐到它的中心。

HTML

<div class="container">
  <div class="center">Center</div>
</div>

CSS

.container {
  display: flex;
  justify-content: center;
}

输出

.container { 显示:flex; justify-content:中心; } .center { 宽度:400 px; 填充:10 px; 背景:# 5 f85db; 颜色:# fff; 粗细:大胆的; 字体类型:大河马字体; } < div class = "容器" > <div class="center"> div居中,文本左对齐 < / div >

您的意思是要垂直居中还是水平居中?你说你指定高度为800像素,并希望div在宽度大于该值时不拉伸…… 要水平居中,可以使用margin: auto;属性。此外,你还必须确保body和html元素没有任何边距或填充:

html, body { margin: 0; padding: 0; }
#centeredDiv { margin-right: auto; margin-left: auto; width: 800px; }

将这个类添加到你想居中的div(它应该有一个设置的宽度):

.marginAutoLR
{
    margin-right:auto;
    margin-left:auto;
}

或者,添加边缘到你的div类,像这样:

.divClass
{
    width:300px;
    margin-right:auto;
    margin-left:auto;
}

没有指定div宽度的定心:

body {
  text-align: center;
}

body * {
  text-align: initial;
}

body div {
  display: inline-block;
}

这有点像<center>标签,除了:

所有直接内联的子元素(例如。<h1>)的<center>也将定位到居中 根据浏览器默认值,内联块元素可以有不同的大小(与display:block设置相比)

出于某种原因,之前的答案对我都不起作用。这对我来说很管用,而且在不同的浏览器中也同样适用:

.center {
    text-align: center;
    height: 100%;

    /* Safari, Opera, and Chrome */
    display: -webkit-box;
    -webkit-box-pack: center;
    -webkit-box-align: center;

    /* Firefox */
    display: -moz-box;
    -moz-box-pack: center;
    -moz-box-align: center;

    /* Internet Explorer 10 */
    display: -ms-flexbox;
    -ms-flex-pack: center;
    -ms-flex-align: center;
}