Как выровнять кнопку справа
Как можно передвинуть красную кнопку так что бы было как на фото? Ссылка на CodePen
.element-grid__element < display: flex; flex-direction: column; margin: 0; padding: 0; list-style-type: none; border-radius: 10px; overflow: hidden; max-width: 282px; >.element-grid__like-button < background-image: url(../../../images/like-pic.svg); padding: 0; margin-top: 6px; width: 21px; height: 20px; background-color: white; outline: none; border: none; background-repeat: no-repeat; background-position: center; cursor: pointer; z-index: 2; >.element-grid__like-button:hover < opacity: 0.8; transition: all 1s ease-in; >.element-grid__photo < width: 282px; height: 282px; margin: 0; padding: 0; >.element-grid__text < font-family: 'Inter', ‘Arial’, sans-serif; font-style: normal; font-weight: 900; font-size: 24px; line-height: 29px; color: black; padding: 0; margin: 0; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; max-width: 88%; >.element-grid__text-container < margin: 0; background: #FFFFFF; display: flex; justify-content: space-between; padding: 25px 19px 31px; align-items: center; >.element-grid < margin: 0; padding: 0; display: grid; grid-gap: 20px 18px; grid-template-columns: repeat(auto-fit, 282px); justify-content: center; >.popup-add < display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); width: 100%; height: 100%; >.popup-add__container < display: flex; flex-direction: column; justify-content: center; align-items: center; background: #FFFFFF; box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.15); border-radius: 10px; max-width: 430px; position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); >.popup-add__close < border: none; padding: 0; position: absolute; cursor: pointer; background: url(../images/сlose-icon.svg) no-repeat center; width: 40.7px; height: 40.7px; right: -40.7px; top: -40.7px; >.popup-add__close:hover < opacity: 0.6; transition: all .1s ease-in; >.popup-add__title < font-weight: 900; font-family: 'Inter', ‘Arial’, sans-serif; font-size: 24px; line-height: 29px; color: black; width: 358px; margin: auto; padding-top: 34px; >@media screen and (max-width: 550px) < .popup-add__title < max-width: 230px; font-size: 16px; line-height: 20px; >> .popup-add__input < border: none; margin: 29.74px auto 0; padding-bottom: 13.3px; border-bottom: 1px solid rgba(0, 0, 0, 0.2); width: 358px; font-size: 14px; line-height: 17px; outline: none; color: #C4C4C4; >.popup-add__input:nth-of-type(1) < margin-top: 54px; >.popup-add__input:active < outline: 2px solid blue >@media screen and (max-width:750px) < .popup-add__input < width: auto; >> .popup-add__save-button < font-family: 'Inter', ‘Arial’, sans-serif; background: black; border: none; border-radius: 2px; height: 50.15px; width: 358px; margin: auto; color: white; margin: 48px auto 36.5px; cursor: pointer; >.popup-add__save-button:hover < background: rgba(0, 0, 0, 0.8); transition: all .1s ease-in; >@media screen and (max-width: 550px) < .popup-add__save-button < width: 200px; height: 35px; >> .popup-add_active < display: block; >.element-grid__like-button_active < background-image: url(../images/likepic.PNG); >.element-grid__delite-button < width: 20px; height: 20px; z-index: 4; /*position:absolute;*/ top: 0; right: 0; background-color: red; >.elements < max-width: 882px; margin: 76px auto 0; padding: 0; >.123a
эту кнопку ---------->
Отслеживать
11.5k 4 4 золотых знака 22 22 серебряных знака 38 38 бронзовых знаков
задан 27 июл 2020 в 15:32
user389240 user389240
@Vasily на карточках слева есть красная кнопка. Но я я хочу ее передвинуть вправо , что бы было как на фотографии (образец). По идее эта кнопка должна удалять картинку , но почему то не удаляет (хотя скрипт удаления вроде прописал)
– user389240
27 июл 2020 в 16:05
3 ответа 3
Сортировка: Сброс на вариант по умолчанию
Задайте position: relative родительскому блоку, внутри него сделайте элемент, которому зададите position: absolute , тогда вы сможет манипулировать расположением absolute элемента с помощью css-свойств top , left , right , bottom
*, *::before, *::after < box-sizing: border-box; margin: 0; padding: 0; >img < display: block; max-width: 100%; >.card < width: 100vw; height: 100vh; margin: 0 auto; position: relative; >.card img < object-fit: cover; position: absolute; height: 100%; width: 100%; z-index: -1; >button < --white: rgba(255, 255, 255, 1); --black: rgba(0, 0, 0, 1); outline: none; border: 1px solid var(--white); background-color: var(--black); padding: 5px 10px; font-size: 5vw; cursor: pointer; color: var(--white); transition: border-color 0.2s linear, background-color 0.2s linear, color 0.2s linear; >button:hover < color: var(--black); border-color: var(--black); background-color: var(--white); >.card button
Helloooo
Вариант с вашим кодом:
Я задал position: relative для .element-grid__element , position: absolute задал для .element-grid__delite-button
document.addEventListener("DOMContentLoaded", function() < let popupAdd = document.querySelector(".popup-add") let popupAddEditForm = document.querySelector(".profile__add-button") let popupAddClose = document.querySelector(".popup-add__close") let popupLoad = document.querySelector(".popup-add__save-button") popupLoad.addEventListener("click", function(e) < e.preventDefault() addSubmitHandler() >) function toggleAddPopup() < popupAdd.classList.toggle("popup-add_active") >function addForm() < toggleAddPopup() >popupAddEditForm.addEventListener("click", addForm) popupAddClose.addEventListener("click", toggleAddPopup) const initialCards = [< name: "Архыз", link: "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/arkhyz.jpg" >, < name: "Челябинская область", link: "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/chelyabinsk-oblast.jpg" >, < name: "Иваново", link: "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/ivanovo.jpg" >, < name: "Камчатка", link: "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/kamchatka.jpg" >, < name: "Холмогорский район", link: "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/kholmogorsky-rayon.jpg" >, < name: "Байкал", link: "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/baikal.jpg" >] const toggleLikeButton = (e) => < e.target.classList.toggle("element-grid__like-button_active") >const addPhotoElement = (caption, imageLink) => < const elementTemplate = document.querySelector("#photo-elements-template").content const photoElement = elementTemplate.cloneNode(true) photoElement.querySelector(".element-grid__photo").src = imageLink photoElement.querySelector(".element-grid__text").textContent = caption const photoElementsList = document.querySelector(".element-grid") photoElementsList.prepend(photoElement) document.querySelector(".element-grid__like-button").addEventListener("click", toggleLikeButton) >const addCards = (array) => < array.forEach((item) =>< addPhotoElement(item.name, item.link) >) > addCards(initialCards) const addSubmitHandler = (e) => < const newPhotoElementName = document.getElementById("name").value const newPhotoElementLink = document.getElementById("link").value addPhotoElement(newPhotoElementName, newPhotoElementLink) toggleAddPopup() >>) const deleteCard = (e) =>
.profile__add-button < display: none; >.element-grid__delite-button < float: right; width: 20px; height: 20px; background-color: red; >.element-grid__element < display: flex; flex-direction: column; margin: 0; padding: 0; list-style-type: none; border-radius: 10px; overflow: hidden; max-width: 282px; position: relative; >.element-grid__like-button < background-image: url(../../../images/like-pic.svg); padding: 0; margin-top: 6px; width: 21px; height: 20px; background-color: white; outline: none; border: none; background-repeat: no-repeat; background-position: center; cursor: pointer; z-index: 2; >.element-grid__like-button:hover < opacity: 0.8; transition: all 1s ease-in; >.element-grid__photo < width: 282px; height: 282px; margin: 0; padding: 0; >.element-grid__text < font-family: 'Inter', ‘Arial’, sans-serif; font-style: normal; font-weight: 900; font-size: 24px; line-height: 29px; color: black; padding: 0; margin: 0; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; max-width: 88%; >.element-grid__text-container < margin: 0; background: #FFFFFF; display: flex; justify-content: space-between; padding: 25px 19px 31px; align-items: center; >.element-grid < margin: 0; padding: 0; display: grid; grid-gap: 20px 18px; grid-template-columns: repeat(auto-fit, 282px); justify-content: center; >.popup-add < display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); width: 100%; height: 100%; >.popup-add__container < display: flex; flex-direction: column; justify-content: center; align-items: center; background: #FFFFFF; box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.15); border-radius: 10px; max-width: 430px; position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); >.popup-add__close < border: none; padding: 0; position: absolute; cursor: pointer; background: url(../images/сlose-icon.svg) no-repeat center; width: 40.7px; height: 40.7px; right: -40.7px; top: -40.7px; >.popup-add__close:hover < opacity: 0.6; transition: all .1s ease-in; >.popup-add__title < font-weight: 900; font-family: 'Inter', ‘Arial’, sans-serif; font-size: 24px; line-height: 29px; color: black; width: 358px; margin: auto; padding-top: 34px; >@media screen and (max-width: 550px) < .popup-add__title < max-width: 230px; font-size: 16px; line-height: 20px; >> .popup-add__input < border: none; margin: 29.74px auto 0; padding-bottom: 13.3px; border-bottom: 1px solid rgba(0, 0, 0, 0.2); width: 358px; font-size: 14px; line-height: 17px; outline: none; color: #C4C4C4; >.popup-add__input:nth-of-type(1) < margin-top: 54px; >.popup-add__input:active < outline: 2px solid blue >@media screen and (max-width:750px) < .popup-add__input < width: auto; >> .popup-add__save-button < font-family: 'Inter', ‘Arial’, sans-serif; background: black; border: none; border-radius: 2px; height: 50.15px; width: 358px; margin: auto; color: white; margin: 48px auto 36.5px; cursor: pointer; >.popup-add__save-button:hover < background: rgba(0, 0, 0, 0.8); transition: all .1s ease-in; >@media screen and (max-width: 550px) < .popup-add__save-button < width: 200px; height: 35px; >> .popup-add_active < display: block; >.element-grid__like-button_active < background-image: url(../images/likepic.PNG); >.element-grid__delite-button < width: 20px; height: 20px; z-index: 4; position:absolute; top: 10px; right: 10px; background-color: red; >.elements
Как выровнять кнопку по центру используя CSS и HTML
Чтобы расположить кнопку в центре HTML страницы, можно использовать 3 разных подхода:
Разберем их подробнее.
Как использовать margin: auto для центрирования кнопки
Первый и, возможно, самый простой вариант — добавить кнопке CSS свойство margin: 0 auto , а затем добавить display: block , чтобы сделать кнопку в центре.
button < margin : 0 auto ; display : block ; >
margin: 0 auto — это краткая форма установки верхнего и нижнего полей в 0 и левого и правого полей на авто.
Автоматическое поле — это то, что заставляет кнопку центрироваться. Тут важно, чтобы кнопка находилась внутри блока.
Как центрировать кнопку с помощью HTML тега div
Второй вариант — обернуть кнопку тегом div , а затем использовать text-align: center для центрирования кнопки внутри этого .
Как будто ты размещаешь текст по центру.
div < text-align : center ; >
div> button>Centered buttonbutton > div >
Обратной стороной этого подхода является то, что каждый раз, когда ты хочешь центрировать кнопку, тебе придется создавать новый элемент div только для этой кнопки.
А если у тебя много кнопок, которые требуют частого обновления стиля, поддерживать их быстро становится проблемой.
В таком случае лучше использовать первый вариант.
Короче говоря, если вы настаиваете на использовании этого подхода, сделайте это только для редких кнопок.
Как центрировать кнопку с помощью CSS flexbox
Третий вариант — использовать flexbox для центрирования кнопки.
Этот подход идеален, если ты уже используешь flexbox на веб-странице, а кнопка находится внутри родительского элемента.
Чтобы центрировать кнопку с помощью flexbox , ты должен сделать 2 вещи:
сначала добавь display: flex к родительскому элементу кнопки, чтобы активировать функции flexbox
затем добавь justify-content: center , чтобы кнопка была по центру
В приведенном ниже примере div является родительским элементом кнопки.
div < display : flex ; justify-content : center ; >
div> button>Centered buttonbutton > div >
Теперь ты знаешь 3 способа центрирования кнопки в CSS!
Как выровнять кнопку по правому краю в html?
Вариант 1 — float: right; . Вариант 2 — flex. Вариант 3 — grid. Вариант 4 — position: absolute/fixed .
Ответ написан более трёх лет назад
Комментировать
Нравится 2 Комментировать
Ankhena @Ankhena Куратор тега CSS
Нежно люблю верстку
1. Родителю text-align: right 2. Родителю flex — margin-left: auto кнопке — justify-content: flex-end родителю 3. Абсолют кнопке
и еще пачка других возможностей
Расположение кнопки внутри блока
Подскажите пожалуйста, как сделать, чтобы кнопка располагалась в верхнем правом углу этой прямоугольной картинки img?
Заранее благодарю за помощь !!
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
CSS Расположение элемента в углу внутри блока здравствуйте. Подскажите как расположить icon_favorite или span в правом верхнем углу <div.
Position fixed кнопки внутри блока Коллеги, доброго времени суток, делаю макет и встал на не понятном до селе мне моменте. Суть.
Внутри родительского блока сделать отступ дочернего блока сверху автоматически Здравствуйте, как с помощью css внутри родительского блока сделать отступ дочернего блока сверху.
1372 / 785 / 262
Регистрация: 17.07.2021
Сообщений: 1,670
Записей в блоге: 11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
html > head > style > * { padding : 0 ; margin : 0 ; box- sizing: border- box; } .container { position : relative ; width : min- content ; } . close { position : absolute ; right : 10px ; top : 10px ; } .closeButton { color : white ; background-color : transparent ; background-repeat : no-repeat ; border : none ; cursor : pointer ; overflow : hidden ; outline : none ; display : block ; } img { display : block ; background : #000; } style > head > body > div class = "container" > img class = "center-img" width = "400" height = "300" > img > div class = "close" > button class = "closeButton" > Xbutton > div > div > script > script > body > html >
Регистрация: 14.06.2012
Сообщений: 353
Hele , картинка не может содержать блок. Вообще-то она ничего не может содержать) А ещё она не имеет закрывающей тег. Но есть несколько грамотных вариантов, например:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
div class = "center-img" > button class = "close" > Кнопкаbutton > div > style > . center - img{ display : flex; align- items: flex- start ; /*двигаем верх*/ justify- content : flex- end ; /*двигаем вправо*/ background : url ( "pape-2828083_1280.jpg" ) ; /*путь к картинке*/ width : 160px ; /*шиирина картинки*/ height : 160px ; /*высота*/ } style >
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь
Выравнивание блока footer внутри другого блока Подскажите пожалуйста, как убрать разрыв между блоком Footer и div’ом cont. <article> <div.
Расположение блока справа <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>статья</title> .
Расположение навигационного блока Добрый времени суток! Столкнулся с проблемой центрирования nav-блока. Никаким образом не хочет.
Расположение текста блока-ссылки с aspect ratio 1:1 Стоит задача в создании сетки 3х3, в которой будут всегда квадратные кнопки-ссылки. Но проблема.
Расположение одного блока под двумя другими Здравствуйте. Ниже привожу коды страницы. Проблема: блок меню почему-то не получается разместить.