<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
I'm surprised this has not been mentioned yet, but the simplest way to do this would be by setting the height, margin (and width, if you want) using viewport sizes. As you might know, total height of the viewport = 100vh. Say you want the height of you container to occupy 60% (60vh) of the screen, you can divide the rest (40vh) equally between the top and the bottom margin so that the element aligns itself in the centre automatically. Setting the margin-left and margin-right to auto, will make sure the container is centred horizontally.
.container { 宽度:60大众;/ *可选* / 高度:60 vh; 利润率:20vh auto; 背景:# 333; } < div class = "容器" > < / div >
其他回答
我在看Laravel的视图文件,注意到他们完美地将文本居中。我立刻想起了这个问题。 他们是这样做的:
<html>
<head>
<title>Laravel</title>
<!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>-->
<style>
.container {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table;
}
.inside {
text-align: center;
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container">
<div class="inside">This text is centered</div>
</div>
</body>
结果如下所示:
我认为有两种方法使div中心对齐通过CSS。
.middleDiv {
position : absolute;
width : 200px;
height : 200px;
left : 50%;
top : 50%;
margin-left : -100px; /* half of the width */
margin-top : -100px; /* half of the height */
}
这是最简单最好的方法。演示请访问以下链接:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
如果你正在研究新的浏览器(IE10+),
然后你可以使用transform属性在中心对齐一个div。
<div class="center-block">this is any div</div>
这个的css应该是:
.center-block {
top:50%;
left: 50%;
transform: translate3d(-50%,-50%, 0);
position: absolute;
}
这里的问题是,您甚至不必指定div的高度和宽度,因为它会自行处理。
同样,如果你想把一个div放在另一个div的中心,那么你可以指定外部div的相对位置,然后这个CSS开始为你的div工作。
工作原理:
当您将left和top指定为50%时,div将位于页面的右下四分之一,其左上端固定在页面的中心。 这是因为,左/顶部属性(当以%给出时)是基于外部div(在您的情况下,窗口)的高度计算的。
但是transform使用元素的高度/宽度来决定转换,因此div将向左移动(50%宽度)和向上移动(50%高度),因为它们是以负号给出的,因此将其对齐到页面的中心。
如果你必须支持旧的浏览器(抱歉,包括IE9),那么表格单元格是最流行的方法。
抱歉回复晚了 最好的办法是
div {
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
}
上边距和左边距应该根据你的div框大小
在父元素上使用display:grid并将margin:auto设置为居中元素即可:
请看下面的片段:
html,身体{ 宽度:100%; 高度:100%; 保证金:0; 填充:0; } .container { 显示:网格; 高度:90%; 背景颜色:蓝色; } .content { 保证金:汽车; 颜色:白色; } < div class = "容器" > <div class="content"> cented div here</div> < / div >