Center a flexbox item in the container, if there is already an item to the left
This question already has an answer here:
You want to center blocks inside parent block so that one block will be not counted, so you need to get it out of the flow, set it position: absolute
. There you can read more.
I would do it like this:
<div>
<a class="a">→</a>
<a class="b">here <br> is a load of text.<br>I want it to be centered in the div,<br>not shifted to the right</a>
</div>
div {
position relative;
display: flex;
justify-content: center;
align-items: center;
max-width: 22em;
height: 22em;
border:1px solid blue;
a.a {
position: absolute;
left: 0;
align-self: center;
}
a.b {
display: flex;
justify-content: center;
align-self: center;
flex: 1;
}
}
https://jsfiddle.net/km5gdrcm/2/
Position the icon a absolutely, this takes it out of the document flow so it won't affect the centered box.
<div class="container">
<a class="icon">→</a>
<a class="centered-box">here <br> is a load of text.<br>I want it to be centered in the div,<br>not shifted to the right</a>
</div>
.centered-box {
flex: 1;
}
.container {
position: relative;
display: flex;
width: 20em;
align-items: center;
border:1px solid blue;
text-align:center;
}
.icon {
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
}
Fiddle: https://jsfiddle.net/nt4shjn5/
Fiddle with padding added to container to avoid overflowing the text over the icon: https://jsfiddle.net/nt4shjn5/1/
链接地址: http://www.djcxy.com/p/13260.html上一篇: 你(真的)写出异常安全的代码吗?