调整浏览器大小时屏幕中心文本

时间:2017-11-23 12:58:54

标签: html css

我有两个div容器在屏幕上创建100%叠加,第二个在屏幕中心创建一些文本。

我希望在调整页面大小时,文本会保留在屏幕中央。我在某个事件上显示并隐藏了容器。

   #container
    {
      background-color: rgba(0, 0, 0, 1);
      display: none;
      height: 100%;
      width: 100%;
      z-index: 999;
      position: absolute;      
    }
    #text
    {
      bottom: 0;
      left: 0;
      position: fixed;
      right: 0;
      text-align:center;
      top: 50%;
    }
    <div id="container">
      <div id="text">some text here</div>
    </div>

 

5 个答案:

答案 0 :(得分:1)

希望这会对你有所帮助。

jQuery(document).ready(function($) {
    $("button").click(function(event) {
     $("#container").show();
    });
});
#container{
  background-color: rgba(0, 0, 0, 1);
  display: none;
  height: 100%;
  width: 100%;
  z-index: 999;
  position: absolute; 
}
#text{
  left: 0;
  position: fixed;
  right: 0;
  text-align:center;
  top: 50%;
  transform: translateY(-50%);
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="container">
  <div id="text">some text here</div>
</div>
<button>Show popup</button>

答案 1 :(得分:1)

#text {
  position: absolute;
  display: inline;
  left: 50%;
  top:50%;
  transform: translate(-50%, -50%);
}
<div id="container">
  <div id="text">some text here</div>
</div>

将位置设置为'绝对'然后向左和向上设置为50%以定位屏幕的div中心。 (如果您不想垂直找到屏幕的div中心,则删除顶部:50%)。 然后你的div的左上角将成为浏览器的中心。 要准确定位屏幕中心,请将div的大小移动一半,然后移动到其高度的上半部分。

答案 2 :(得分:0)

如果您正在寻找垂直对齐目的。转到display: table属性

#container {
    background-color: rgba(0, 0, 0, 1);
    display: table;
    height: 100%;
    width: 100%;
    position: absolute;
}

#text {
    text-align: center;
    color: #ffffff;
    display: table-cell;
    vertical-align: middle;
}
<div id="container">
    <div id="text">some text here</div>
</div>

答案 3 :(得分:0)

这里是你的代码.. HTML:

<div id="container">
  <div id="text">some text here</div>
</div>

CSS

#container
{
  background-color: rgba(0, 0, 0, 1);
  display: none;
  height: 100vh;
  width: 100vw;
  z-index: 999;
  position: absolute;      
}
#text
{
  font:10px;
  color:white;
  bottom: 0;
  left: 0;
  position: fixed;
  right: 0;
  text-align:center;
  top: 50%;
}

Jquery的:

$("body").click(function(){
$("#container").css("display","block");
});

答案 4 :(得分:0)

使用display flex属性。

#container{
display:flex;
align-items: center;
height:100%;
}
#text{
width:100%;
text-align:center;
}

希望它能帮到你。

相关问题