高级前端
css
【Q282】对一个非定长宽的块状元素如何做垂直水平居中

对一个非定长宽的块状元素如何做垂直水平居中

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 284 (opens in a new tab)

Author 回答者: huxiamei (opens in a new tab)

flex布局

Author 回答者: XJHxjh0118 (opens in a new tab)

定位 .parent{ position: relative; } .child{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

Author 回答者: linlai163 (opens in a new tab)

css position

        .container {
            position: relative;
        }
        .container .item {
            width: 100px;
            height: 50px;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }

Author 回答者: shfshanyue (opens in a new tab)

css position

        .container {
            position: relative;
        }
        .container .item {
            width: 100px;
            height: 50px;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }

非定宽了,你这个不行呀

Author 回答者: linlai163 (opens in a new tab)

css position

        .container {
            position: relative;
        }
        .container .item {
            width: 100px;
            height: 50px;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }

非定宽了,你这个不行呀

面试官说,做题前要好好读题。😭

Author 回答者: jkLennon (opens in a new tab)

https://github.com/shfshanyue/Daily-Question/issues/10 (opens in a new tab)

Author 回答者: wuzqZZZ (opens in a new tab)

<div class="parent">
  <div class="child">123456</div>
</div>
.parent {
  display: flex;
  height: 200px;
  background-color: #222;
}
 
.child {
  background-color: red;
  margin: auto;
}

Author 回答者: LIyu2001 (opens in a new tab)

---方法一: 父级flex .container{display: flex; justify-content: center;
  align-items: center;} ---方法二:父级grid .container{display: grid;
  justify-content: center; align-items: center;} ---方法三:父级定位,子maigin
  .container{position: relative;} .container .item{position: absolute; top: 0;
  bottom: 0; left: 0; right: 0; margin: auto;} ---方法四:父级定位,子位移
  .container{position: relative;} .container .item{position: absolute; top: 50%;
  left: 50%; transform: translate(-50%, -50%) ;};

Author 回答者: perterHUAN (opens in a new tab)

top: 0;
bottom: 0;
left: 0;
right: 0;

方法三设置成和父元素一样大了,这符合题意吗?