- Как изменить ширину элемента. Свойство width
- Для чего использовать свойство width
- Элемент на странице шире, чем вы задумали
- Ширина элемента больше ширины родителя
- Материалы по теме
- How to Force a Button or Link to be 100% Width CSS Tutorial
- 12 Comments on “How to Force a Button or Link to be 100% Width CSS Tutorial”
- Увеличить зону кликабельности ссылки — HTML/CSS
- Плохой
- Злой
- Хороший
- width
- Пример
- width
Как изменить ширину элемента. Свойство width
CSS-свойство width определяет ширину элемента на странице. Оно позволяет управлять размером элемента и адаптировать его под разные размеры экрана.
Свойство width записывается так:
Ширина может быть автоматической — если её не указать, то она будет иметь значение auto . В этом случае браузер сам решит, какую ширину установить элементу на основе размеров родительского элемента и содержимого.
Если вы хотите управлять шириной, укажите значение — определённую вами ширину элемента. Тогда она будет постоянной или будет меняться в зависимости от всего вокруг на странице. Можно использовать единицы измерения — например, px , % , em , rem .
Вот так — в пикселях, тогда ширина будет постоянной. В этом случае — 200 пикселей.
А так — в процентах, тогда ширина будет меняться при изменении размеров окна. В этом случае — 50% от ширины родительского элемента.
В любом варианте к ширине нужно относиться внимательно, чтобы всё сошлось с макетом.
Если пока не понимаете, зачем здесь фигурные скобки — прочитайте о селекторах.
Для чего использовать свойство width
Один из вариантов — чтобы ограничить ширину текстового блока и улучшить читаемость на больших экранах. Например, когда вы делаете блог и хотите, чтобы текст не растягивался на всю ширину экрана. Как на этой странице.
Вот так мы стилизуем элемент с шириной 50%, который находится по центру экрана.
Относительные единицы измерения помогают создавать адаптивные страницы. Попробуйте сами — контейнер будет тянуться вместе с окном браузера.
Другой вариант использования — создать сетку на основе флексбоксов с фиксированными размерами колонок.
Это очень простой пример сеток, но если интересно, прочитайте наше пошаговое рукововодство по созданию адаптивных сеток.
С шириной всё вообще непросто — иногда с непривычки могут произойти странные ситуации, из-за которых придётся долго гуглить. Давайте о них поговорим.
Элемент на странице шире, чем вы задумали
Виновато свойство box-sizing , которое по умолчанию имеет значение content-box .
Почему так. Когда вы задаете ширину элемента с помощью свойства width , она применяется только к содержимому элемента и не учитывает его отступы, поля ( padding и margin ) и границы ( border ). Это может привести к тому, что общая ширина элемента будет больше, чем ожидалось.
Например, у нас есть такой элемент с классом box :
И мы применяем следующие стили — ширина 100 пикселей, отступы по 10 пикселей со всех сторон и вдобавок пятипиксельную границу.
Тогда вспоминаем математику и считаем — общая ширина элемента с заданной шириной 100px будет на самом деле равна 130px .
100px + 2 × 10px (отступы) + 2 × 5px (границы) = 130px
Как починить. Нужно включить отступы и границы в заданную ширину элемента. Для этого используйте свойство box-sizing со значением border-box :
Теперь общая ширина элемента будет равна 100px , так как отступы и границы будут включены в указанную ширину. Такое поведение следует учитывать при вёрстке и подготовке макетов, чтобы в результате не оказалось непредвиденных сюрпризов.
Ширина элемента больше ширины родителя
Если ширина нашего элемента случайно оказалась больше, чем у родительского, то он не вместится. И будет как-то так:
Создаём два вложенных элемента с классами parent и child .
И стилизуем их. У parent ширина 100 пикселей, а у child — 200.
Выше вы уже видели, что произойдёт в этом случае — элемент child с синим фоном будет выходить за пределы родительского элемента с рамкой.
Конечно, иногда так поступают специально — например, чтобы иллюстрации в блоге выходили за пределы колонки с текстом и были покрупнее.
Хотя если указать только width без ограничений, то при уменьшении окна картинка не вместится.
Теперь дочерний элемент не будет выходить за пределы родительского элемента, даже если его ширина увеличивается.
Ну и не забывайте тестировать сайты и проверять их в разных браузерах — это важный навык для всех веб-разработчиков в любом году.
👉 Все браузеры поддерживают свойство width , так что смело пользуйтесь.
Материалы по теме
- Не шириной единой — свойство height ещё запутаннее, но тоже важное
- Чем отличаются margin и padding (и как их больше никогда не перепутать)
- Как создавать адаптивные сетки
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
How to Force a Button or Link to be 100% Width CSS Tutorial
These are instructions on how to make an HTML link or button expand to be as wide as its parent element. Maybe you have been confused in the past and that darn link just never wants to grow.
Here is the CSS you are going to want to apply to that link.
text-align : center ; /*This will result in centering the link text, which is probably what you want -brianjohnsondesign.com*/
And the corresponding HTML:
The secret here is that you need to use display:block; to actually force the button to grow to the full width. You also can’t really use left or right margins or padding, as they will just mess up the width and cause it to be off-center or larger than its container. Top or bottom margins or padding won’t cause any problems, however.
Keep in mind, as well, you need to make sure that the parent div or element of the link must be the width you are trying to force this button to be. Check and make sure it has a width!
Brian Johnson is a website developer and designer living in Minneapolis, Minnesota with a passion for code and WordPress. He spends his days building WordPress websites for small businesses, developing new code with the online community, and living life.
12 Comments on “How to Force a Button or Link to be 100% Width CSS Tutorial”
This doesn’t work if you want a margin on the side of your button. I found that you can work around this by using: width: calc(100% – 6em); where you set your subtraction distance (as in 6em above) along with your margins to give the appropriate appearance that you want.
Увеличить зону кликабельности ссылки — HTML/CSS
Необходимо сделать ссылкой не только подзаголовок, но и саму картинку. Есть три способа три: назовем их хороший, плохой и злой.
Плохой
Просто обернуть и заголовок, и картинку в ссылку следующим образом:
Злой
Обернуть все в одну ссылку:
Хороший
Разместить ссылку в заголовке, а затем расширить область ссылки на всю карточку с помощь псевдоэлемента :before:
div position: relative; > a:before content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; >
Можно использовать любой из этих трех способов, но лично я предпочитаю последний.
width
Свойство width отвечает за ширину элемента. С его помощью мы можем увеличивать или уменьшать ширину строчно-блочных ( inline — block ) и блочных ( block ) элементов. На строчные элементы это свойство не будет иметь никакого влияния.
Строчно-блочные ( inline — block ) элементы по умолчанию подстраиваются под ширину контента, лежащего у них внутри.
Блочные ( block ) элементы по умолчанию имеют ширину 100%. Если представить сайт как документ с текстом, то блочный элемент займёт всю строку, на которой стоит.
Кроме фиксированной ширины можно задавать элементу минимальную ширину min — width или максимальную ширину max — width .
В современном CSS есть логический аналог этого свойства — inline — size .
Пример
Скопировать ссылку «Пример» Скопировано
Я — блочный элемент!Ястрочно-блочныйэлемент!div class="block">Я — блочный элемент!div> div class="inline-block">Яdiv> div class="inline-block">строчно-блочныйdiv> div class="inline-block">элемент!div>
Не меняем display для .block , поскольку уже является блочным:
.block background-color: #2E9AFF;> .inline-block display: inline-block; background-color: #F498AD;>
.block background-color: #2E9AFF; > .inline-block display: inline-block; background-color: #F498AD; >
Теперь любой текст будет занимать не больше, чем 50% от ширины карточки 🎉
width
The width property in CSS specifies the width of the element’s content area. This “content” area is the portion inside the padding, border, and margin of an element (the box model).
In the example above, elements that have a class name of .wrap will be 80% as wide as their parent element. The accepted values are any of the length values, in addition to some keywords we’ll cover later. Width can be overridden by the closely correleated properties min-width and max-width .
When using percentage (%) for width, authors must be aware that the percentage is based on the element’s parent, or in other words, the width of the containing block. If your parent is set at 480px – as demonstrated by our demo – then the percentage is based on that value. So in our case 50% of 480px leaves us with 240px as a computed pixel value. Note that width applies to all elements except non-replaced or inline elements, table rows and row groups (i.e. thead , tfoot and tbody ). There seems to be a slight mismatch as far as how HTML defines non-replaced elements and how CSS defines it, but we’re referring to it the way CSS does: elements whose content is not defined by the tag itself, such as an with the src attribute. For absolutely positioned elements whose containing block is based on a block container element, the percentage is calculated with respect to the width of the padding box of that element.
With some special keyword values, it is possible to define width (and/or height) according to the content of the element.
The min-content value is the smallest measure that would fit around its content if all soft wrap opportunities within the box were taken. The best example for this kind of value is a properly written figure element:
If we wanted that figure element to essentially be the size of that image, so the text wraps at the edges of the image. We could float it left or right, because float will exhibit that same kind of shrink-to-fit behavior, but what if we wanted to center it? min-content allows us to center it:
Because we’ve assigned min-content to the figure element, it takes the minimum width it can have when taking all soft wrap opportunities (like spaces between words) so that the content still fits in the box.
The max-content property refers to the narrowest measure a box could take while fitting around its content – if no soft wrap opportunities within the element were taken. Check out what happens if we apply this to our simple kitten/figure demo:
Because the caption is very longer than the image is wide (it doesn’t take any soft wrap opportunity, like the spaces between words), it means it has to display the caption on a single line, thus the figure is as wide as that line.
The fit-content value is roughly equivalent to margin-left: auto and margin-right: auto in behaviour, except it works for unknown widths. For instance, let’s say we need to center an inline navigation across the page. Your best bet would be to apply text-align: center to the ul , and display: inline-block to the li . This would give you something like this:
However, the blue background (from the ul element) spreads across the entire document because the ul is a block-level element, which means its width is restricted only by its containing element. What if we want to have the blue background collapsing around the list items? fit-content to the rescue!
With fit-content and margin: 1em auto , this works like a charm and only the navigation has a colored background, not the whole document width. If you’re into this sort of thing, you’ll be happy to know the formula to define the size of a fit-content length is:
fit-content = min(max-content, max(min-content, fill-available))
IE | Edge | Firefox | Chrome | Safari | Opera |
---|---|---|---|---|---|
All | All | All | All | All | All |
Android Chrome | Android Firefox | Android Browser | iOS Safari | Opera Mobile |
---|---|---|---|---|
All | All | All | All | All |
Source: caniuse