-2

On most of my sites, I put information into a div that has rounded corners with a fox shadow. I was wondering if there is a way to have this parent div automatically center itself vertically & horizontally while changing its height & width based on its children. Below is as close as I have gotten but the div stays to the upper left of my page. It seems to fit the content well but the position is not close to where I'd want it.

.appRoundedShadow {
  display: inline-block;
  justify-content: center;
  align-items: center;
  height: auto;
  width: auto;
  background-color: white;
  padding: 25px;
  border-radius: 20px;
  border: 1px outset gray;
  box-shadow: 10px 10px 5px #888888;
}

I haven't been successful with flexbox.

Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
smuldr
  • 315
  • 1
  • 12

2 Answers2

2

Using flex is easy. The think you must not forget is: The child is vertically centered on the parent height. So you must set a minimum to works or height of parent is equal to child height (and no top/bottom margin are required to center it)

/* Normalize */
html, body { 
  padding: 0;
  margin: 0;
}
html {
  height: 100%; 
}
body {
  min-height: 100%;
  display: flex;
}
.appRoundedShadow {
  margin:auto;

  background-color: white;
  padding: 25px;
  border-radius: 20px;
  border: 1px outset gray;
  box-shadow: 10px 10px 5px #888888;
}
<div class="appRoundedShadow"></div>
Arthur
  • 4,870
  • 3
  • 32
  • 57
1

flexbox should be the solution for your problem, read more about CSS flexbox here

html,body{
  width:100%;
  height:100%;
  margin:0;
}
.appRoundedShadow {
display: inline-block;
height: auto;
width: auto;
background-color: white;
padding: 25px;
border-radius: 20px;
border: 1px outset gray;
box-shadow: 10px 10px 5px #888888;
}
.container{
  width:100%;
  height:100%;
  display:flex;
  justify-content:center;
  align-items:center;
}
<div class="container">
<div class="appRoundedShadow">Some Text</div>
</div>
xTrimy
  • 804
  • 9
  • 23