简体   繁体   中英

Vertically Aligning Elements

I'm trying to understand how to center elements within a div. I have this basic code I am working with and am trying to get the 'This is a button' element to be in the center

    <body>

<div style="width:960px;background-color:#d7d7d7;">

  <div style="
  width:400px;
  padding:10px;
  height:auto;
  background-color:#006699;
   display:inline-block;
  ">

  <p> Vivamus vel sapien. Praesent nisl tortor, laoreet eu, dapibus quis, egestas non, mauris. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vivamus vel sapien. Praesent nisl tortor, laoreet eu, dapibus quis, egestas non, mauris. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
  </div>      

  <div style="
  width:100px;
  padding:10px;
  height:auto;
  background-color:#b1b1b1;
  float:right;
  display:inline-block;
  margin:auto!important;
  vertical-align:middle;
  ">

  <p>This is a button</p>

  </div>    

</div>

</body>

It's essentially 1 div, divided into 2 with text on the left hand side and a 'This is a button' label to be in the center of the right side, but I can;t figure out how to get it to center, I've tried all sorts of methods.

All help/advice is appreciated.

You can do it with the following markup:

<div class="container">
  <div class="left">
    <p>Vivamus vel sapien. Praesent nisl tortor, laoreet eu, dapibus quis, egestas non, mauris. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vivamus vel sapien. Praesent nisl tortor, laoreet eu, dapibus quis, egestas non, mauris. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
  </div>
  <div class="right">
    <p class="button">Click Me!</p>
  </div>
</div>

CSS:

.container {
  width: 960px;
  background-color: #d7d7d7;
  overflow: hidden;
  display: table;
}

.left,
.right {
  box-sizing: border-box;
  width: 50%; 
  display: table-cell;
}

.left {
  padding: 20px 10px;
  background: #006699;
}

.right {
  text-align: center;
  vertical-align: middle;
}

.button {
  border: 1px solid green;
  display: inline-block;
}

http://jsfiddle.net/yh6mn/1/

No matter what's the size of your paragraph - the button to the right will alway be aligned to the absolute center.

Negative margins could be used for this. See example: http://codepen.io/anon/pen/xhoBz

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