假設我有這個 for 回圈來創建 HTML。
let content;
for (let i = 0; i < 4; i ) {
if (i % 2 == 0) {
content = "Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8]"
} else {
content = "Stack Overflow is a question and answer website for professional and enthusiast programmers."
}
document.body.innerHTML = `
<div class='whole'>
<p>${content}</p>
<button class='buttons'>Click</button>
<button class='buttons'>ADD</button>
</div>`
}
body {
display: grid;
grid-column-gap: 50px;
grid-row-gap: 50px;
grid-template-columns: repeat(2, auto);
}
.whole {
width: 200px;
}
.buttons {
position: relative;
top: 10px;
left: 200px
}
這一切都很好,但我想讓按鈕位置始終與其他按鈕保持相同的位置(垂直)。
現在在我的代碼中,按鈕的高度將受到長度和其他子元素 ( p) 的影響。我嘗試使用position:absoluteor position:sticky,但它們都不能解決我的問題。
有沒有辦法使子元素的位置對唯一的子元素是絕對的?
我想要達到的效果是所有按鈕都可以始終與其他按鈕具有相同的垂直位置。

uj5u.com熱心網友回復:
如果你想要實作的是將按鈕垂直對齊在同一行,你可以簡單地使用 CSS flexbox in .whole. 通過強制 flex 方向column,然后強制在其子項之間插入空格justify-content: space-between,您幾乎可以實作您想要的:
let content;
for (let i = 0; i < 4; i ) {
if (i % 2 == 0) {
content = "Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8]"
} else {
content = "Stack Overflow is a question and answer website for professional and enthusiast programmers."
}
document.body.innerHTML = `
<div class='whole'>
<p>${content}</p>
<button class='buttons'>Click</button>
</div>`
}
body {
display: grid;
grid-column-gap: 50px;
grid-row-gap: 50px;
grid-template-columns: repeat(2, auto);
}
.whole {
width: 200px;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.buttons {
position: relative;
width: min-content;
left: 100%;
}
uj5u.com熱心網友回復:
這是使用網格的解決方案。使整個網格專案,然后使用 place-self 和 grid-row-start 將按鈕放在最后;您可以在 CSS 技巧中了解網格的完整作業方式。
let content;
for (let i = 0; i < 4; i ) {
if (i % 2 == 0) {
content = "Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8] Stack Overflow is a question and answer website for professional and enthusiast programmers."
} else {
content = "Stack Overflow is a question and answer website for professional and enthusiast programmers."
}
document.body.innerHTML = `
<div class='whole'>
<p>${content}</p>
<button class='buttons'>Click</button>
<button class='buttons'>ADD</button>
</div>`
}
body {
display: grid;
grid-column-gap: 50px;
grid-row-gap: 50px;
grid-template-columns: repeat(2, auto);
}
.whole {
display: grid;
width: 200px;
column-gap: 5px;
}
.buttons {
position: relative;
grid-row-start: 2;
height: 20px;
place-self: end;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/418220.html
標籤:
