简体   繁体   English

垂直对齐元素

[英]Vertically Aligning Elements

I'm trying to understand how to center elements within a div. 我试图了解如何在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. 基本上是1格,分为2格,左侧带有文本,“ This is a button”标签位于右侧中心,但我不知道如何将其居中,我我尝试了各种方法。

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: 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/ 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 参见示例: http//codepen.io/anon/pen/xhoBz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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