Daily-Question icon indicating copy to clipboard operation
Daily-Question copied to clipboard

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

Open shfshanyue opened this issue 4 years ago • 9 comments

shfshanyue avatar Apr 24 '20 12:04 shfshanyue

flex布局

huxiamei avatar Aug 06 '20 07:08 huxiamei

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

XJHxjh0118 avatar Nov 25 '20 01:11 XJHxjh0118

css position

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

linlai163 avatar Jan 08 '21 09:01 linlai163

css position

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

非定宽了,你这个不行呀

shfshanyue avatar May 21 '21 04:05 shfshanyue

css position

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

非定宽了,你这个不行呀

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

linlai163 avatar Oct 23 '21 16:10 linlai163

https://github.com/shfshanyue/Daily-Question/issues/10

jkLennon avatar Nov 17 '21 10:11 jkLennon

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

.child {
  background-color: red;
  margin: auto;
}

wuzqZZZ avatar Aug 28 '22 08:08 wuzqZZZ

---方法一:父级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%);
}

LIyu2001 avatar Sep 17 '22 13:09 LIyu2001

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

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

perterHUAN avatar Sep 25 '23 10:09 perterHUAN