使用 :after 添加第二个元素到 div
Add a second element to div with :after
嗨,我有关注 div:
.box {
width: 100px;
height: 20px;
border: 1px solid black;
}
.box:after {
content: '';
width: 20px;
height: 20px;
background-color: blue;
}
<div class="box"></div>
我想用伪 class after
添加第二个 div 到 .box
。我以为它会像这样工作,但没有任何反应。它应该是这样的:
如何使用 after
执行此操作?
谢谢。
您的代码是正确的,唯一缺少的是该元素的 属性 显示。只需在 :after
元素上添加一个 display: block
。要轻松操作伪元素,请将主要元素设为 position: relative
,然后将 :after
设为 position: absolute
,然后根据 .box
div
放置它,类似这 :
.box {
width: 100px;
height: 20px;
border: 1px solid black;
position: relative; /* Made it relative */
}
.box:after {
content: '';
position: absolute;
display: block;
width: 20px;
height: 20px;
border: 1px solid blue;
top: -1px; /* To compensate the border on the main element */
background-color: blue;
left: 100%; /* To place it after the main element */
}
如果您确实需要另一个 div,请尝试添加一些 javascript,就像这样
$(document).ready(function() {
$('.box').append('<div class="another-box"></div>');
});
.box {
width: 100px;
height: 20px;
position: relative;
border: 1px solid black;
}
.box:after {
content: '';
width: 20px;
bottom: -1px;
right: -21px;
top: -1px;
position: absolute;
background-color: blue;
}
<div class="box"></div>
试试这个
.box {
width: 100px;
height: 20px;
border: 1px solid black;
}
.box:after {
content: '';
width: 20px;
height: 20px;
background-color: blue;
display:block;
float:right;
}
<div class="box"></div>
嗨,我有关注 div:
.box {
width: 100px;
height: 20px;
border: 1px solid black;
}
.box:after {
content: '';
width: 20px;
height: 20px;
background-color: blue;
}
<div class="box"></div>
我想用伪 class after
添加第二个 div 到 .box
。我以为它会像这样工作,但没有任何反应。它应该是这样的:
如何使用 after
执行此操作?
谢谢。
您的代码是正确的,唯一缺少的是该元素的 属性 显示。只需在 :after
元素上添加一个 display: block
。要轻松操作伪元素,请将主要元素设为 position: relative
,然后将 :after
设为 position: absolute
,然后根据 .box
div
放置它,类似这 :
.box {
width: 100px;
height: 20px;
border: 1px solid black;
position: relative; /* Made it relative */
}
.box:after {
content: '';
position: absolute;
display: block;
width: 20px;
height: 20px;
border: 1px solid blue;
top: -1px; /* To compensate the border on the main element */
background-color: blue;
left: 100%; /* To place it after the main element */
}
如果您确实需要另一个 div,请尝试添加一些 javascript,就像这样
$(document).ready(function() {
$('.box').append('<div class="another-box"></div>');
});
.box {
width: 100px;
height: 20px;
position: relative;
border: 1px solid black;
}
.box:after {
content: '';
width: 20px;
bottom: -1px;
right: -21px;
top: -1px;
position: absolute;
background-color: blue;
}
<div class="box"></div>
试试这个
.box {
width: 100px;
height: 20px;
border: 1px solid black;
}
.box:after {
content: '';
width: 20px;
height: 20px;
background-color: blue;
display:block;
float:right;
}
<div class="box"></div>