Lyn*_*son 5 html css css-position
父级具有百分比宽度。我正在寻找一种简单的方法来保持子 div:.wrp位于其父级的中心:.contr即使它溢出父级甚至溢出页面。我尝试过绝对定位,但它在这里似乎不起作用。
例子:
有想法吗?
body {
overflow: hidden;
padding: 5%;
text-align: center;
}
.contr { /* << contr = Container */
width: 40%;
height: 95%;
background-color: #eee;
}
.wrp { /* << wrp = Wrapper */
width: 5rem;
height: 5rem;
margin: auto;
background-color: #bbb;
opacity: 0.75;
}
.expand {
animation-name: expand;
animation-duration: 4s;
animation-iteration-count: infinite;
}
@keyframes expand {
50% {
width: 30rem;
}
}Run Code Online (Sandbox Code Playgroud)
<head>
<style>
@import url( 'https://necolas.github.io/normalize.css/latest/normalize.css' );
* {
box-sizing: border-box;
outline: 1px solid #555;
}
.v-cntr { /* << v-cntr = Vertically Centered */
position: relative;
top: 50%;
transform: translateY( -50% );
}
html, body {
height: 100%;
}
</style>
</head>
<body>
<div class="contr v-cntr">
<div class="wrp v-cntr expand">
stay<br>centered in<br>parent
</div>
</div>
</body>Run Code Online (Sandbox Code Playgroud)
编辑:为了澄清我希望子 div 溢出它的父级
尝试position: absolute使用left:50%和translateX(-50%):
body {
overflow: hidden;
padding: 5%;
text-align: center;
}
.contr { /* << contr = Container */
height: 95%;
width: 40%;
background-color: #eee;
}
.wrp { /* << wrp = Wrapper */
width: 5rem;
height: 5rem;
margin: auto;
background-color: #bbb;
opacity: 0.75;
}
.expand {
animation-name: expand;
animation-duration: 4s;
animation-iteration-count: infinite;
}
@keyframes expand {
50% {
width: 30rem;
}
}
/*new*/
.wrp.v-cntr {
position: absolute;
left: 50%;
transform: translate(-50%, -50%)Run Code Online (Sandbox Code Playgroud)
<head>
<style>
@import url( 'https://necolas.github.io/normalize.css/latest/normalize.css' );
* {
box-sizing: border-box;
outline: 1px solid #555;
}
.v-cntr { /* << v-cntr = Vertically Centered */
position: relative;
top: 50%;
transform: translateY( -50% );
}
html, body {
height: 100%;
}
</style>
</head>
<body>
<div class="contr v-cntr">
<div class="wrp v-cntr expand">
stay<br>centered in<br>parent
</div>
</div>
</body>Run Code Online (Sandbox Code Playgroud)