Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 在div中居中元素_Html_Css - Fatal编程技术网

Html 在div中居中元素

Html 在div中居中元素,html,css,Html,Css,大家都有一些关于在容器中居中文本和div的问题 这是我的密码笔。 我的问题是: 一,。使div中的任何元素文本和图像垂直居中的最佳方法是什么。 2.在集装箱舱上使用固定高度是一个好主意还是一个坏主意 <header> <div class="logo"> logo </div> <h1 class="SiteTitle"> Registrar's <span>Office</span> &

大家都有一些关于在容器中居中文本和div的问题

这是我的密码笔。

我的问题是:

一,。使div中的任何元素文本和图像垂直居中的最佳方法是什么。 2.在集装箱舱上使用固定高度是一个好主意还是一个坏主意

 <header>
  <div class="logo">
    logo
  </div>
  <h1 class="SiteTitle">
    Registrar's <span>Office</span>
  </h1>
  <div class="search">
    Search
  </div>
  <div class="az">
    A -> Z Index
  </div>
  <div class="sublinks">
    <a href=""> About</a>
    <p>Main Office</p>
  </div>
</header>


@import 'susy';
* { box-sizing: border-box; }
header {
  background:red;
  width:100%;
  height: 100%;
  @include container(100%);
  height:100px;



  .logo{
    @include span(3 of 12);
    border:1px solid #fff;
    height: 100%;

  }

  h1{
    @include span(5 of 12);
    border:1px solid #fff;
    height: 100%;
    font-size:40px;
  }
 .search, {
   @include span(2 of 12);
   border:1px solid #fff;
   height: 100%;
 }


  .az {
    @include span(2 of 12  last);
        border:1px solid #fff;
    height: 100%;


  }
.sublinks {
  background:blue; 
  clear:both;
  text-align:right;
  @include span(12 of 12 );
  @include break;
  a, p {
    display:inline-block
  }
}
}

根据我的经验,固定高度不一定是个问题。如果您有一个固定高度的容器和一个固定高度的子元素,那么您可以使用css轻松地垂直居中。例如,如果您有一个100px的容器和一个50px的子容器,请将其从顶部定位为25px

对于更多的动态元素,我通常使用javascript。如果使用jQuery,可以设置如下函数:

function centerElement(container, child) {
     var containerHt = $(container).height();
     var childHt = $(child).height();
     var top = Math.round( (containerHt - childHt) / 2 );
     $(child).css('top', top);
}
当然,容器需要有相对位置,子容器需要有绝对位置。左边的值也可能是一个问题,在这种情况下,您可以让函数找到两个元素的宽度,并将它们的差异减半

最后,还有另一个CSS解决方案,它有时可以工作,尽管它可能会导致一些其他问题,特别是溢出:隐藏:

#container { display: table; }
#child { display: table-cell; vertical-align: middle; }

如果你知道信息不会溢出,那么使用固定高度也不错。否则,您可以编写一个jQuery脚本来设置高度。这样,您可以确保它们都是相同的,然后绝对将元素垂直放置在其父元素内。本文可能会有帮助,嘿,Nate,感谢您的回复!我尝试了显示表单元格,但它似乎破坏了susy2浮动元素。是的,我几乎总是使用jQuery。如果要处理图像,请记住调用$window.load中的函数,而不是$document.ready中的函数