猿问

如何水平和垂直居中元素

如何水平和垂直居中元素

我试图垂直居中我的标签内容,但是当我添加CSS样式时display:inline-flex,水平文本对齐消失。


如何为每个标签创建文本对齐x和y?


* { box-sizing: border-box; }

#leftFrame {

  background-color: green;

  position: absolute;

  left: 0;

  right: 60%;

  top: 0;

  bottom: 0;

}

#leftFrame #tabs {

  background-color: red;

  position: absolute;

  top: 0;

  left: 0;

  right: 0;

  height: 25%;

}

#leftFrame #tabs div {

  border: 2px solid black;

  position: static;

  float: left;

  width: 50%;

  height: 100%;

  text-align: center;

  display: inline-flex;

  align-items: center;

}

<div id=leftFrame>

  <div id=tabs>

    <div>first</div>

    <div>second</div>

  </div>

</div>


慕斯709654
浏览 433回答 3
3回答

红糖糍粑

如果CSS3是一个选项(或者你有一个后备),你可以使用transform:.center&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;right:&nbsp;50%; &nbsp;&nbsp;&nbsp;&nbsp;bottom:&nbsp;50%; &nbsp;&nbsp;&nbsp;&nbsp;transform:&nbsp;translate(50%,50%); &nbsp;&nbsp;&nbsp;&nbsp;position:&nbsp;absolute;}与上面的第一种方法不同,您不希望使用left:50%使用负面翻译,因为IE9 +中存在溢出错误。利用正数值,您将看不到水平滚动条。

开心每一天1111

将盒子垂直和水平居中的最佳方法是使用两个容器:外侧容器:应该有&nbsp;display: table;内部容器:应该有&nbsp;display: table-cell;应该有&nbsp;vertical-align: middle;应该有&nbsp;text-align: center;内容框:应该有&nbsp;display: inline-block;应调整水平文本对齐,除非您希望文本居中演示:body {&nbsp; &nbsp; margin : 0;}.outer-container {&nbsp; &nbsp; display: table;&nbsp; &nbsp; width: 80%;&nbsp; &nbsp; height: 120px;&nbsp; &nbsp; background: #ccc;}.inner-container {&nbsp; &nbsp; display: table-cell;&nbsp; &nbsp; vertical-align: middle;&nbsp; &nbsp; text-align: center;}.centered-content {&nbsp; &nbsp; display: inline-block;&nbsp; &nbsp; text-align: left;&nbsp; &nbsp; background: #fff;&nbsp; &nbsp; padding : 20px;&nbsp; &nbsp; border : 1px solid #000;}<div class="outer-container">&nbsp; &nbsp;<div class="inner-container">&nbsp; &nbsp; &nbsp;<div class="centered-content">&nbsp; &nbsp; &nbsp; &nbsp; Center this!&nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp;</div></div>另见这个小提琴!居中在页面中间:要将内容置于页面中间,请将以下内容添加到外部容器中:position : absolute;width: 100%;height: 100%;这是一个演示:body {&nbsp; &nbsp; margin : 0;}.outer-container {&nbsp; &nbsp; position : absolute;&nbsp; &nbsp; display: table;&nbsp; &nbsp; width: 100%;&nbsp; &nbsp; height: 100%;&nbsp; &nbsp; background: #ccc;}.inner-container {&nbsp; &nbsp; display: table-cell;&nbsp; &nbsp; vertical-align: middle;&nbsp; &nbsp; text-align: center;}.centered-content {&nbsp; &nbsp; display: inline-block;&nbsp; &nbsp; text-align: left;&nbsp; &nbsp; background: #fff;&nbsp; &nbsp; padding : 20px;&nbsp; &nbsp; border : 1px solid #000;}<div class="outer-container">&nbsp; &nbsp;<div class="inner-container">&nbsp; &nbsp; &nbsp;<div class="centered-content">&nbsp; &nbsp; &nbsp; &nbsp; Center this!&nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp;</div></div>另见这个小提琴!
随时随地看视频慕课网APP
我要回答