Align contents inside a div

后端 未结 8 2014
时光取名叫无心
时光取名叫无心 2020-12-22 15:50

I use css style text-align to align contents inside a container in HTML. This works fine while the content is text or the browser is IE. But otherwise it does not work.

相关标签:
8条回答
  • 2020-12-22 16:12

    Below are the methods which have always worked for me

    1. By using flex layout model:

    Set the display of the parent div to display: flex; and the you can align the child elements inside the div using the justify-content: center; (to align the items on main axis) and align-items: center; (to align the items on cross axis).

    If you have more than one child element and want to control the way they are arranged (column/rows), then you can also add flex-direction property.

    Working example:

    .parent {
      align-items: center;
      border: 1px solid black;
      display: flex;
      justify-content: center;
      height: 250px;
      width: 250px;
    }
    
    .child {
      border: 1px solid black;
      height: 50px;
      width: 50px;
    }
    <div class="parent">
      <div class="child"></div>
    </div>

    2. (older method) Using position, margin properties and fixed size

    Working example:

    .parent {
      border: 1px solid black;
      height: 250px;
      position: relative;
      width: 250px;
    }
    
    .child {
      border: 1px solid black;
      margin: auto;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      position: absolute;
      width: 50px;
    }
    <div class="parent">
      <div class="child"></div>
    </div>

    0 讨论(0)
  • 2020-12-22 16:19

    Just another example using HTML and CSS:

    <div style="width: Auto; margin: 0 auto;">Hello</div>
    
    0 讨论(0)
提交回复
热议问题