- Обратная связь
- How to Right Align a Button with CSS
- Solution with the CSS float property
- Example of aligning a button to the right with the CSS float property:
- Solution with the CSS text-align property
- Example of aligning a button to the right with the CSS text-align property:
- Example of aligning a button to the right with the «right» value of the text-align property:
- Solution with the CSS justify-content property
- Example of aligning a button to the right with the «flex-end» value of the justify-content property:
- Приклейте кнопку к правой стороне div
- Ответы (7)
- Как прижать меню навигации к правой стороне сайта?
Обратная связь
form /* Стили к самой форме */ <
text-align:right;
font-family:Arial, Helvetica, sans-serif; /* Говорится, какой шрифт будет использоваться, данном случае Arial */
font-size:12px; /* Размер шрифта 12 пикселей */
padding:10px; /* Отступы внутри формы шириной 10 пикселей */
border: 1px solid #ddd; /* Сплошная рамка вокруг формы шириной 1 пиксель и цветом #ddd */
border-top: 0px; /* Говорит, что вверху рамки не должно быть */
width:350px; /* Ширина 350 пикселей */
background:#C0C0C0; /* Фоновый цвет формы gray */
>
form .input /* Стили для класса input */ <
text-align:right;
width: 230px; /* Ширна 230 пикселей */
border: 1px solid #ddd; /* Сплошная рамка вокруг шириной 1 пиксель и цветом #ddd */
>
form textarea /* Стили к тегу textarea */ <
width: 230px; /* Ширина 230 пикселей */
border: 1px solid #ddd; /* Сплошная рамка вокруг шириной 1 пиксель и цветом #ddd */
>
.n /* Стили к классу n */ <
text-align:right;
font-size:12px; /* Размер шрифта 12 пикселей */
font-family:Arial, Helvetica, sans-serif; /* Говорится, какой шрифт будет использоваться, данном случае Arial */
color:#333; /* Цвет текста #333 */
text-align:center; /* Выравнивание текста */
background:#fff; /* Фоновый цвет #fff */
width:360px; /* Ширина 360 пикселей */
padding:5px; /* Отступы от всех краев размером 5 пикселей */
border:1px solid #ddd; /* Сплошная рамка вокруг шириной 1 пиксель и цветом #ddd */
>
#table<
text-align:right;
>
#body>
#h1<
Font-size:60px;
font-family:Monotype Corsiva,fantasy;
text-align:center;
color:black
>/*Форм. заголовка. Размер шр, стиль, место, цвет, отступы автоматические*/
#td<
font-face:FrankRuehl,fantasy;
font-size:30px;
color:black;
te
можно запихнуть всю форму в div, а ему уже в css прописать float:right;
Объясняю:
1. пишешь
далее идет код всей формы
и закрываешь
2. в css:
#form <
float:right; /*выравнивание по правому краю*/
margin-top:0; /*значение отступа сверху*/
margin-right:0; /*значение отступа справа*/
>
Если значение margin=0, отступа не будет, а если нужен — к примеру так:
#form <
float:right; /*выравнивание по правому краю*/
margin-top:10px; /*значение отступа сверху*/
margin-right:20px; /*значение отступа справа*/
>
Если что дополнительно объяснить нужно — пиши в лс
How to Right Align a Button with CSS
In this snippet, you can find various examples of right aligning a button by using the following CSS properties: float, text-align, and justify-content. Below, we’ll demonstrate solutions with each of them.
Solution with the CSS float property
Use the CSS float property with the “right” value to right align a button. The alignment technique you use depends on the situation, but here, it’s important to use the float property.
Example of aligning a button to the right with the CSS float property:
html> html> head> title>Title of the document title> style> div < width: 200px; overflow: hidden; border: 1px solid #ff1100; clear: both; > p < margin-bottom: 10px; > input.right < float: right; > style> head> body> div> p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. p> p> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. p> input type="button" value="Click here" class="right"> div> body> html>
Solution with the CSS text-align property
It is also possible to align the element to the right by using the CSS text-align property.
In the example below, we set the text-align to «right» for the element and use the «left» value of the same property for the element.
Example of aligning a button to the right with the CSS text-align property:
html> html> head> title>Title of the document title> style> div < width: 200px; border: 1px solid #ff1100; text-align: right; > p < margin-bottom: 10px; text-align: left; > style> head> body> div> p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. p> p> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. p> button type="button">Button button> div> body> html>
If you want to move the button to the right, you can also place the button within a element and add the text-align property with its «right» value to the «align-right» class of the .
Example of aligning a button to the right with the «right» value of the text-align property:
html> html> head> title>Title of the document title> style> div < width: 200px; border: 1px solid green; > p < margin-bottom: 10px; > .align-right < text-align: right; border: 0; > style> head> body> div> p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. p> p> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. p> div class="align-right"> button type="button">Button button> div> div> body> html>
Solution with the CSS justify-content property
In our example below, we set the display to «flex» and add the justify-content property with the «flex-end» value to the class of our element.
Example of aligning a button to the right with the «flex-end» value of the justify-content property:
html> html> head> title>Title of the document title> style> div < width: 250px; border: 1px solid pink; > p < margin-bottom: 20px; > .flex-end < background-color: pink; padding: 10px 0; display: flex; justify-content: flex-end; > style> head> body> div> p> Flexbox is a single dimensional layout, which means that it lays items in one dimension at a time, either as a row, or as a column, but not both together. This can be opposed to the two-dimensional model - CSS Grid Layout, which lays the items in two dimensions simultaneously (rows and columns together). p> p> In HTML, the default values of the display property are taken from the behaviors which are described in the HTML specifications or from the browser or user default stylesheet. p> div class="flex-end"> button type="button">Button button> div> div> body> html>
Приклейте кнопку к правой стороне div
http://jsfiddle.net/kn5sH/ Что мне нужно добавить, чтобы прилепить кнопку справа от div на той же строке, что и заголовок? HTML:
- Правая сторона кнопки должна быть на расстоянии x пикселей от правого края div.
- Он должен быть на той же строке, что и заголовок.
- Должен содержаться в div (такие вещи, как float или относительное позиционирование, визуально выталкивают его из div)
Какие методы CSS можно использовать для этого? Спасибо.
Ответы (7)
Обычно я бы рекомендовал плавать, но из ваших 3 требований я бы предложил следующее:
position: absolute; right: 10px; top: 5px;
Не забудьте position: relative; в родительском div
Спасибо, это отлично работает. Я пробовал это, но забыл об атрибуте «верхний», который помещал его ниже div. — person Andrew; 30.05.2013
Это зависит от того, чего именно вы хотите добиться.
Если вы просто хотите, чтобы он был справа, то я бы рекомендовал не использовать абсолютную позицию, потому что она открывает целую банку червей в будущем.
HTML также может быть неизменен:
тогда CSS должен быть чем-то вроде:
Вы можете увидеть это в действии здесь: http://jsfiddle.net/azhH5/
Если вы можете изменить HTML, все становится немного проще:
Вы можете увидеть его в действии: http://jsfiddle.net/8WA3k/1/.
Если вы хотите, чтобы кнопка находилась в той же строке, что и текст, вы можете добиться этого, выполнив следующие действия:
Ясно, что в примере вам не пришлось бы настраивать верхнее поле для указанного размера шрифта
Как видите, он не выдвигается из , он остается внутри. это достигается двумя вещами: отрицательной маржей на и overflow: hidden; на
РЕДАКТИРОВАТЬ 2:
Я только что увидел, что вы также хотите, чтобы он был немного в стороне от поля справа. Это легко достижимо с помощью этого метода. Просто добавьте margin-right: 1em; к , вот так:
Вы можете увидеть это в действии здесь: http://jsfiddle.net/QkvGb/
Не могли бы вы подробнее рассказать, как этот overflow: hidden помогает в этой ситуации? и этот отрицательный запас тоже. — person JohnnyQ; 01.12.2016
Как прижать меню навигации к правой стороне сайта?
Ребят, учусь 🙂 Помогите пожалуйста, нужно разместить меню навигации напротив логотипа. подскажите как правильно прописать, чтоб все ровненьки и красивенько.
Код ниже. Скрин с проблемой тоже.
Заранее спасибо!
- HOME
- ABOUT
- WORK
- BLOG
- CONTACT
body < background: #efefef; margin: 0; padding: 0; font: 16px/24px Arial, Tahoma, sans-serif; >.header < background: #87509c;/*Цвет хедера*/ >.logo < padding-top: 150px; /*Отступ сверху*/ padding-left: 300px;/*Отступ справа*/ >.nav < list-style: none; /*откл. маркеров*/ >.nav li < float: left; /* Выстраивание элементов списка в один ряд. */ margin-right: 0px; /* создание отступов для того, чтобы не сливались пункты меню. */ font-family: Arial, Helvetica, sans-serif; /* Указание типа шрифта. */ font-size: 16px; /* Размер текста в ссылках. */ >.nav li a < display: block; /* Изменение отображения на блочное для того чтобы иметь возможность задать внутренние отступы. */ padding: 10px 15px; /* Внутри блочные отступы. */ background: #87509c; /* Цвет блоков меню. */ color: #efefef; /* Цвет текста в блоках меню. */ text-decoration: none; /* Устранение подчёркивания ссылок. */ position: relative; /* Это необходимо при использовании Internet Explorer 6 для того, чтобы ссылка по всей своей площади была «кликабельной». */ >.nav li a:hover < background: #643a79; /* Цвет блока при наведении курсора. */ color: #efefef; /* Цвет текста при наведении курсора. */ >