简体   繁体   中英

Move div under centered div

我的问题

As you can see in the image the element with the class “inner“ is centered inside the “outer“ div, for that I used this stack overflow post. I have tried getting the Hello World paragraph to appear underneath the centered div without cheating with the margin property, but no success.

 .outer { position: relative; height: 80%; width: 100%; } .inner { position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); vertical-align: middle; } 
 <div class="outer"> <div class="inner"></div> <p>Hello World</p> </div> 

If you're centering multiple elements, put them inside one container and center that container, like so:

 html, body { height: 100%; } .outer { background: blue; position: relative; height: 100%; width: 100%; } .center { position: absolute; transform: translate(-50%, -50%); top: 50%; left: 50%; /* offset margin by 1/2 height of addtl elements */ margin-top: 23px; } .inner { background: lightblue; width: 300px; height: 100px; } p { background: lightgray; text-align: center; margin: 16px 0 0; height: 30px; /* 30 + 16 = 46 ==> 46 / 2 = 23 (offset) */ } 
 <div class="outer"> <div class="center"> <div class="inner"></div> <p>Hello World</p> </div> </div> 

I would recomend something like this : https://jsfiddle.net/jw6vcxh7/

.outer {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  border: 1px solid red;
  width: 500px;
  height: 800px;
}

.inner {
  height: 100px;
  width: 100px;
  margin: 0 auto;
  border: 1px solid blue;
}

Was your intention to have it both vertically and horizontally centered?

If so you can add

.outer p {
  position: relative;
  top: 50%;
  left: 50%;
  display:block;
}

Or if you need it just horizontially centered then the following should do the trick...

.outer {
  position: relative;
  height: 80%;
  width: 100%;
  border: 1px solid red;
}
.inner {
  position: relative;
  height: 100px;
  width: 100px;
  display: block;
  margin: 0px auto;
  vertical-align: middle;
  border: 1px solid blue;
}
.outer p {
  display: block;
  margin: 0px auto;
  width: 80%;
  text-align: center;
  background: #ccc;
  }
}

A good reference for centering divs can be found here http://vanseodesign.com/css/vertical-centering/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM