У меня проблема с выравниванием флажка рядом с текстом.
Я разрабатываю простое приложение со списком дел. Я создал элемент абзаца, используя JavaScript, и я создал флажок, используя элемент span.
listElementid в моем CSS происходит от JavaScript, где я установил идентификатор элемента абзаца на listElement.
Вот к чему я стремлюсь:
Вот что у меня есть на данный момент:
var toDoItems = [];
var i = 1;
var userInput;
var listElement;
var checkBox;
document.getElementById("addItem").onclick = function() {
userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
stylePara();
document.getElementById("item-list").
append(listElement);
}
function stylePara() {
listElement = document.createElement("p");
listElement.id = "listElement";
listElement.innerHTML = userInput;
}#listElement {
width: 500px;
background: red;
margin: 0 auto;
border: 1px solid green;
color: white;
text-align: center;
text-transform: capitalize;
padding: 20px;
}<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel = "stylesheet" type = "text/css">
<h1>My Tasks</h1>
<h4><span id = "number1"></span> tasks</h4>
<button id = "addItem">Add item</button>
<div id = "item-list">
<span><input type = "checkbox" id = "checkbox"></span>
</div>Даже сейчас требование неясно. Вы хотели, чтобы рядом с флажком была кнопка Add item?
@brk: Я думаю, очевидно (глядя на картинку), что ему нужен флажок рядом с ярлыком.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


.input-container {
display: -ms-flexbox;
display: flex;
width: 100%;
margin-bottom: 15px;
}
.icon {
padding: 10px;
background: dodgerblue;
color: white;
min-width: 50px;
text-align: center;
}
.input-field {
width: 100%;
padding: 10px;
outline: none;
}
С помощью CSS намного проще выровнять элементы на вашей странице. См. Руководство W3Schools - это просто и легко объяснимо https://www.w3schools.com/howto/howto_css_form_icon.asp
вы можете использовать взломать флажок для этого
.check {
width: 30px;
height: 30px;
background-color: red;
display: inline-block;
}
.text {
display: inline-block;
height: 30px;
line-height: 30px;
vertical-align: top;
padding: 0 5px;
}
input[type = "checkbox"] {
display: none;
}
input[type = "checkbox"]:checked + label {
background-color: black;
}
input[type = "checkbox"]:checked ~ .text {
background-color: #0f0;
color: white;
text-decoration: line-through;
}<input type = "checkbox" id = "a" />
<label class = "check" for = "a"></label><div class = "text">Get shit done</div>Да, ему нужен javascript для добавления элементов
Ok. Поиграйте в этот фрагмент, думаю, вам понравится.
Я на основе эта идея:
настоящий флажок остается невидимым
есть еще один видимый флажок, стилизованный (флажок на самом деле повернутый угол), который меняет свой стиль в соответствии с состоянием реального флажка
Также:
var toDoItems = [];
var i = 1;
var userInput;
var listElement;
var checkBox;
document.getElementById("addItem").onclick = function() {
userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
document.getElementById("item-list").insertAdjacentHTML('beforeend', stylePara());
}
function stylePara() {
var html = '';
html += '<label class = "container">';
html += '<input type = "checkbox">';
html += '<span class = "checkmark"></span>';
html += '<span class = "checklabel">' + userInput + '</span>';
html += '</label>';
return html;
}/* The container */
.container {
width: 100%;
margin-left: 40%;
/*this is the general left margin*/
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default checkbox */
.container input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/* Create a custom checkbox */
.checkmark {
position: absolute;
top: -5px;
left: 0;
height: 35px;
width: 35px;
background-color: #eee;
}
/* On mouse-over, add a grey background color */
.container:hover input~.checkmark {
background-color: #ccc;
}
/* When the checkbox is checked, add a green background */
.container input:checked~.checkmark {
background-color: darkgreen;
}
/* label when unchecked */
.checklabel {
background: red;
color: white;
padding: 5px 20px;
}
/* label when checked */
.container input:checked~.checklabel {
text-decoration: line-through;
background: green;
color: white;
padding: 5px 20px;
}
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.container input:checked~.checkmark:after {
display: block;
top: 10px;
left: 15px
}
/* Style the checkmark/indicator */
.container .checkmark:after {
left: 9px;
top: 5px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}<h1>To do list</h1>
<button id = "addItem">Add item</button>
<div id = "item-list">
<label class = "container">
<input type = "checkbox" checked = "checked">
<span class = "checkmark"></span>
<span class = "checklabel">Example item</span>
</label>
</div>Спасибо, @Sun, за редактирование. Но я восстановил отступы при создании переменной "html" в javascript. Я так и сделал, имитируя отступ HTML. Надеюсь, ты не против.
Ура, как раз то, что я хотел
Начните с этой минимальной разметки и CSS, а затем добавьте свои собственные стили.
.item {
align-items: center;
display: flex;
}
/* Sample custom styles. */
.item p {
background: red;
color: white;
font-size: 20px;
}<div>
<div class = "item">
<input type = "checkbox">
<p>Item 1</p>
</div>
<div class = "item">
<input type = "checkbox">
<p>Item 2</p>
</div>
</div>Они всегда будут выровнены друг с другом, независимо от ваших пользовательских стилей.
Извини, я отредактирую пост