I'm just curious as to what the best way is of aligning a div centrally (vertically and horizontally) inside another div. This example features a red div which I want to vertically & horizontally centre inside the div with the background picture.
What is the best way of doing this so it automatically adapts when resizing the browser window & displaying on mobiles?
The following methods fail:
- position:relative; & top: 50%; - only the very top of the div is centralised but not the rest. Adding a negative margin-top fails because it applies it to the parent element
- margin: 25% auto;
- vertical-align: middle;
- justify-content: center; - presumably only applies to flexboxes
Here is the code:
body{
background: yellow;
margin: 0 auto;
}
#first{
width:100%;
height:550px;
background: url('https://static.pexels.com/photos/30627/pexels-photo-30627.jpg');
background-size: cover;
}
#central{
width:200px;
height:100px;
background: red;
margin: 0 auto;
/*
Why DO THESE FAIL:
position:relative; & top: 50%;
margin: 25% auto;
vertical-align: middle;
justify-content: center; - presumably only applies to flexboxes
*/
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css.css">
<title>title</title>
</head>
<body>
<div id="first">
<div id="central"></div>
</div>
</body>
</html>
Thanks for any help.