-2

How can a centre a div inside another div (both vertically and horizontaly) using CSS? My html is

<div class='outer'><div class='inner'></div></div>

And CSS -

.outer{
position: realative;
top:20%;
left20%;
width:500px;
height:500px;
background:red;
}
.inner{
position:relative;
width:100px;
height:100px;
background:#ff2;
/*code to align in centre*/
}

5 Answers5

0
.center {
  margin: auto;
  width: 50%;
  border: 3px solid green;
  padding: 10px;
}

source: https://www.w3schools.com/css/css_align.asp

Krishan Kumar
  • 394
  • 4
  • 13
0

Add these properties to the outer div:

display: flex;
justify-content: center;
align-items: center;

It will center the content. Alternatively you could add this to the inner:

position: relative;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);

Above it will push itself from all sides.

0

There are multiple approaches since it's a common issue:

Transform

position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);

left and top will translate the item within the parent, and transform will translate it relative to its top left corner.

position: fixed; also work as long as you know the differences between absolute and fixed.

Flexbox

You need to work with the parent. You must set the following properties to the parent:

display: flex;
justify-content: center;
align-items: center;

The child should also have display: flex; for easy handling, but it's not mandatory. position: absolute; is not necessary with this approach.

Cristian Sarghe
  • 782
  • 6
  • 15
0
.inner{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 5.5em;
    background-color: #8880;
}
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Jun 25 '20 at 18:46
  • Mainly doing the help for the answer and that would be like that way! The way wanted to actually do with. – Ayomi Gunasekara Jun 26 '20 at 03:26
-1

Use display:flex;

.outer{
position: realative;
top:20%;
left:20%;
width:500px;
height:500px;
background:red;
display:flex;
align-items:center;
justify-content:center;
}
.inner{
position:relative;
width:100px;
height:100px;
background:#ff2;
/*code to align in centre*/
}

.outer{
position: realative;
top:20%;
left:20%;
width:500px;
height:500px;
background:red;
display:flex;
align-items:center;
justify-content:center;
}
.inner{
position:relative;
width:100px;
height:100px;
background:#ff2;
/*code to align in centre*/
}
<div class='outer'><div class='inner'></div></div>

https://jsfiddle.net/lalji1051/jqxtuvLz/1/

Lalji Tadhani
  • 14,041
  • 3
  • 23
  • 40