How to center align a child div inside a parent di

2020-07-27 05:25发布

i am new to html and css and i couldn't figure out how to center align child div inside parent div.This is my code please answer and solve my problem.

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;
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>

标签: css html
5条回答
等我变得足够好
2楼-- · 2020-07-27 06:09

Your "window" div is CORRECTLY centered within the "page" div.

Your problem is that the page div is not centered within <html></html>.

To achieve this add the following code:

.page
{
...
margin-left:auto;
margin-right:auto;
}
查看更多
在下西门庆
3楼-- · 2020-07-27 06:14

First of all there is nothing called float:center;, float has only 3 valid values which are none, left and right.

Inorder to center any element you need to define some width first and than use margin: auto; to center it horizontally.

Demo

The other way to center an element is to use text-align: center; on the parent element, but this is a dirty way to do so.


You can also use CSS positioning techniques like nesting a absolute element inside a relative positioned element, and than we center it by using left: 50%; and than we deduct 1/2 of the total width of the element by using margin-left: -100px; (total element width say is 200px). You can also center the element vertically.

The other way to have an element centered vertically as well as horizontally is to use display: table-cell; property along with vertical-align: middle;

Demo

查看更多
够拽才男人
4楼-- · 2020-07-27 06:23

Try this,

.window
{
    width:367px;
    height:202px;
    background-color:#c6c6c6;
    margin: auto 0px; /* For center. Apply same to page class*/
}

This may work.

查看更多
仙女界的扛把子
5楼-- · 2020-07-27 06:26

to center horizontally

.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;
}

To center vertically and horizontally both

.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;
}
查看更多
家丑人穷心不美
6楼-- · 2020-07-27 06:27

Please check here:

.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*/
}
查看更多
登录 后发表回答