如何使用css将父div中的子div居中对齐?
我不熟悉html和css,我不知道如何在父div中对齐子div。这是我的代码,请回答并解决我的问题 CSS如何使用css将父div中的子div居中对齐?,css,html,Css,Html,我不熟悉html和css,我不知道如何在父div中对齐子div。这是我的代码,请回答并解决我的问题 CSS .page { position:relative; width:1220px; height:670px; background-image:url('/Users/raghunath/Documents/raghu personel/page07.png'); } .window { float:center; width:367px; height:202px; backgroun
.page {
position:relative;
width:1220px;
height:670px;
background-image:url('/Users/raghunath/Documents/raghu personel/page07.png');
}
.window {
float:center;
width:367px;
height:202px;
background-color:#c6c6c6;
margin-left:auto;
margin-right:auto;
}
* {
padding:0px;
margin:0px;
}
HTML
<div class="page">
<div class="window"><!-- i want to center align this div inside above div -->
</div>
</div>
水平居中
.page
{
position:relative;
width:1220px;
height:670px;
background-image:url('/Users/raghunath/Documents/raghu personel/page07.png');
}
.window
{
position:relative;
width:367px;
height:202px;
background-color:#c6c6c6;
margin:auto;
}
垂直和水平居中
.page
{
position:relative;
width:1220px;
height:670px;
background-image:url('/Users/raghunath/Documents/raghu personel/page07.png');
}
.window
{
position:relative;
top:50%;
left:50%;
width:367px;
height:202px;
background-color:#c6c6c6;
margin-left:-183px;
margin-top:-101px;
}
首先,没有所谓的
float:center
,float
只有3个有效值,它们是无
,左
和右
为了使任何元素居中,您需要首先定义一些宽度,然后使用边距:auto代码>以使其水平居中
另一种使元素居中的方法是使用text align:center在父元素上使用code>,但这是一种肮脏的方式
您还可以使用CSS定位技术,例如将绝对
元素嵌套在相对
定位元素中,然后使用左:50%将其居中然后,我们使用左边距:-100px减去元素总宽度的1/2代码>(总元素宽度
假设为200px
)。您还可以将元素垂直居中
使元素垂直居中和水平居中的另一种方法是使用display:table cell代码>属性与垂直对齐:中间代码>
请检查这里:
.page
{
position:relative;
width:1220px;
height:670px;
background-image:url('/Users/raghunath/Documents/raghu personel/page07.png');
}
.window
{
width:367px;
height:202px;
background-color:#c6c6c6;
margin:0px auto; /* to align center horizontally*/
}
您的“窗口”div在“页面”div中正确居中
您的问题是页面div没有在
中居中
要实现此目的,请添加以下代码:
.page
{
...
margin-left:auto;
margin-right:auto;
}
试试这个
.window
{
width:367px;
height:202px;
background-color:#c6c6c6;
margin: auto 0px; /* For center. Apply same to page class*/
}
这可能会起作用。实际或水平或两者兼而有之?+1很好的解决方案。只是有点疑问。您不需要在父级“display:table”元素中包含“table cell”属性元素吗?@VijetaShetty谢谢您,这不是一种强迫,但是如果您声明一个元素display:cell,它不会有什么害处代码>无显示:表格代码>,同样,这取决于我们试图实现的布局:)